Issue
I'm publishing a notification using NotificationCompat.Builder
class and adding an action button to it called Cancel
I expect, notification should get dismissed by clicking this action button. For this, I send a broadcast and attach notification id to Intent
object by calling putExtra(String, int)
on the Intent
The BroadcastReceiver
receives the id of Notification by calling getIntExtra(String, int)
and cancels the notification by calling NotificationManagerCompat.cancel(id)
But, everytime I try, the value of id
that BroadcastReceiver
receives is 8. Thus, I'm not able to cancel notifications.
Here is my code that adds the action buttons to the notification,
Intent cancelIntent = new Intent(this, NotificationActionReceiver.class);
cancelIntent.putExtra(EXTRA_NOTIFICATION_ID, id);
cancelIntent.setAction(ACTION_DISMISS);
if (BuildConfig.DEBUG)
Log.d(TAG, "Sent id: "+id);
PendingIntent pendingCancelIntent = PendingIntent.getBroadcast(this, 0, cancelIntent, 0);
builder.addAction(R.drawable.ic_dismiss, "Cancel", pendingCancelIntent);
BroadcastReceiver class
public class NotificationActionReceiver extends BroadcastReceiver {
private final static String TAG = NotificationActionReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive(), getAction == "+intent.getAction());
switch (intent.getAction()){
case MyActivity.ACTION_DISMISS:
int id = intent.getIntExtra(MyActivity.EXTRA_NOTIFICATION_ID, -1);
if (BuildConfig.DEBUG)
Log.d(TAG, "Notification id received: "+id);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
managerCompat.cancel(id);
break;
case ....:
....
}
}
}
The log cat always reports that The BroadcastReciver
gets the value for notification id as 8
Solution
I am doing same thing and I am getting proper output:
ComponentName receiver = new ComponentName(context, AlarmReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Log.v(TAG," Notification id:" + model.getNotificationIdForLocalDB());
Intent intent1 = new Intent(context, AlarmReceiver.class);
intent1.putExtra("notification_id", model.getNotificationIdForLocalDB());
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, model.getNotificationIdForLocalDB(), intent1, PendingIntent.FLAG_UPDATE_CURRENT);
And at BroadcastReceiver end :
if(intent != null){
if(intent.getExtras() != null){
notificationId = intent.getExtras().getInt("notification_id",0);
}
}
try to change Pending intent flag 0
to PendingIntent.FLAG_UPDATE_CURRENT
Answered By - Nik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.