通知广播接收器在活动中不工作

Posted

技术标签:

【中文标题】通知广播接收器在活动中不工作【英文标题】:Notification BroadcastReceiver Not Working In Activity 【发布时间】:2020-07-22 20:19:14 【问题描述】:

我有一个通知,并在按下通知中的特定按钮时尝试在活动中运行一个方法。我正在 onCreate 中创建广播接收器:

    //broadcast receiver stuff
    broadcastReceiver = new BroadcastReceiver() 
        @Override
        public void onReceive(Context context, Intent intent) 
            // Code to run
            if (intent.getAction().equals("stop"))
                StartButtonClick();
            
        
    ;
    registerReceiver(broadcastReceiver, new IntentFilter("stop"));

然后我在同一个活动中创建通知(虽然不是在 onCreate 中):

private void ShowNotification()
    //add intent for app to resume when notification is clicked
    PendingIntent reopenAppIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

    //add intent for app to stop service when stop button in notification is clicked
    //this is the intent I am creating for the notification button
    Intent stopIntent = new Intent("stop");
    PendingIntent stopPendingIntent = PendingIntent.getService(this, 1, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    //create notification
    NotificationCompat.Builder notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
            .setContentTitle("Messaging in progress")
            .setContentText("User is late")
            .setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setSmallIcon(R.drawable.ic_message)
            .setContentIntent(reopenAppIntent)
            .addAction(R.drawable.ic_message, "Stop", stopPendingIntent); //here I am adding the intent for the butt that I want to activate the broadcastReceiver
    notificationManager.notify(1, notification.build());

当我单击通知中的按钮时,没有任何反应。我什至在广播接收器的 if 语句上设置了一个断点,并且在按下按钮时什么也没有发生。

【问题讨论】:

【参考方案1】:

试试这个

PendingIntent stopPendingIntent = PendingIntent.getBroadcast(this, 1, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);

而不是

PendingIntent stopPendingIntent = PendingIntent.getService(this, 1, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);

【讨论】:

以上是关于通知广播接收器在活动中不工作的主要内容,如果未能解决你的问题,请参考以下文章

清单与活动中的广播接收器注册

从广播接收器关闭活动

广播接收器正在模拟器和手机上工作,但不是平板电脑

当应用程序关闭时,GCM 广播接收器未检测到 gcm 通知

从通知中发送数据

Android SMS 广播接收器不工作