在创建PendingIntent时指定Intent的Action和Category
在创建PendingIntent时,需要指定Intent的Action和Category,来使其被正确地发送到BroadcastReceiver。具体的代码示例如下:
//创建Intent Intent intent = new Intent(context, MyBroadcastReceiver.class); intent.setAction("com.example.MY_ACTION"); intent.addCategory("android.intent.category.DEFAULT");
//创建PendingIntent PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//创建Notification NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId) .setContentTitle("My Notification") .setContentText("Hello World!") .setSmallIcon(R.drawable.ic_notification) .setContentIntent(pendingIntent) .addAction(R.drawable.ic_action, "My Action", pendingIntent);
//发送Notification NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(notificationId, builder.build());
在上面的代码示例中,我们创建了一个Intent,并指定了它的Action为“com.example.MY_ACTION”,Category为“android.intent.category.DEFAULT”。在创建PendingIntent时,我们使用了这个Intent,并设置了FLAG_UPDATE_CURRENT,表示如果已经存在相同的PendingIntent,则更新它。同时,我们将PendingIntent传递给了通知的addAction()方法中,以便用户可以通过点击它来触发BroadcastReceiver的接收操作。最后,我们通过NotificationManagerCompat来发送通知。
这样一来,我们就可以在点击通知操作时正确地触发BroadcastReceiver的接收操作了。
上一篇:AndroidBroadcastReceiver操作通知点击后存在延迟触发问题。
下一篇:AndroidBtGattblocksscanbecausenoslotsleftforscanfilterhistory。