开发者

How to pass extras within Notification?

开发者 https://www.devze.com 2023-03-10 09:59 出处:网络
I have 2 activities in my app and I would like activity X to popup a notification - once its clicked activity Y will open and read params from the notification.

I have 2 activities in my app and I would like activity X to popup a notification - once its clicked activity Y will open and read params from the notification.

So I've written this:

        String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

    CharSequence tickerText = NOTIFY_TICKER_NAME;
    long when = System.currentTimeMillis();

    Notification notification = new Notification(R.drawable.icon, tickerText, when);

    Context context = getApplicationContext();
    CharSequence contentTitle = "My notification";
    CharSequence contentText = "Hello World!";
    Intent notificationIntent = new Intent(this, PopTask.class);
    notificationIntent.putExtra("task", "http://w开发者_开发百科ww.google.com");
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

    mNotificationManager.notify(1, notification);

Problem is, when I try to read the extras - i get null.

What can I do?

Thanks


oshafran,

In order for putExtra() to work in this case you also have to use setAction(). I'm not entirely sure why this is the case...seems to be some quirk. The value passed in setAction() can be anything.

Try:

Intent notificationIntent = new Intent(this, PopTask.class);
notificationIntent.putExtra("task", "http://www.google.com");
notificationIntent.setAction("MyIntent");


Probably, a bit better solution is to use PendingIntent.FLAG_UPDATE_CURRENT when you create your PendingIntent

Intent intent = new Intent(context, YourActivity.class);
intent.putExtra(YOUR_EXTRA_KEY, "Your Extra");
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号