天天看點

Notification 踩坑記 —— 動态注冊廣播響應點選事件

我們知道通知欄可以通過 PendingIntent 設定點選響應(也可以通過 RemoteView設定),如下:

Intent intent = new Intent(mContext, NotificationReceiver.class);
                intent.setAction(NOTIFICATION_BROADCAST_ACTION);
                PendingIntent pendingIntent = PendingIntent
                        .getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                notification.contentIntent = pendingIntent;
           

但是,以上這樣寫,如果你的廣播NotificationReceiver是動态注冊的,就會無法響應點選事件,這個真的好坑,解決:Intent 換一種 new() 方式

Intent intent = new Intent(NOTIFICATION_BROADCAST_ACTION);
                PendingIntent pendingIntent = PendingIntent
                        .getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                notification.contentIntent = pendingIntent;
           

以上就可以響應點選事件。