How to open a specific activity based on Notification

痴心易碎 提交于 2019-12-12 01:52:24

问题


I am currently working on a reminders app in which the user gets a notification with the name of the reminder and is then redirected to an activity which contains the text of the reminder in detail. I am however, only able to redirect to the same activity each time. I am using this code :

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
notification.setLatestEventInfo(this, title, text, contentIntent);

So this redirects to the MainActivity on clicking the notification. I would like to redirect to a separate screen and then based on a key value display a text on that activity. How do I achieve this ?

Thanks


回答1:


Just change the PendingIntent using another Activity and/or append extra information on the Intent you are using to create the PendingIntent:

Intent launchIntent = new Intent(this, AnotherActivity.class)
launchIntent.putExtra("myKey", "myValue");
//....
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, launchIntent , 0);
notification.setLatestEventInfo(this, title, text, contentIntent);

And than, in you Activity's onCreate():

//...
getIntent().getStringExtra("myKey")
//do your stuff..



回答2:


Just pass the value in the intent . eg.

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
contentIntent.putExtra("phone", value);
contentIntent.putExtra("name", value);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, contentIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);



回答3:


Question has already been anwered and accepted, but here's another method:

int mId = 1;
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, TwoActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
    Notification.Builder builder = new Notification.Builder(this)
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Title")
            .setContentText("Content")
            .setDefaults(Notification.DEFAULT_ALL)
            .setAutoCancel(true)
            .setNumber(1);
    NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(mId, builder.build());


来源:https://stackoverflow.com/questions/29695788/how-to-open-a-specific-activity-based-on-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!