android displaying multiple activity in saved state when notification click

可紊 提交于 2020-01-17 04:56:29

问题


I have a notification on my app. It works in foreground well. When i`m in a other activity and press home button after that i click notification. It opens given activity, but i need to display previous activity in a saved state.

        Notification note = new Notification(R.drawable.service_state_0,
            getResources().getText(R.string.serviceStarted),
            System.currentTimeMillis());
    Intent i = new Intent(this, StartingActivity_.class);

    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
    note.setLatestEventInfo(this,
            getResources().getText(R.string.app_name), getServiceStateDescription(CustomService.this), pi);
    note.flags |= Notification.FLAG_NO_CLEAR;
    note.flags |= Notification.FLAG_ONGOING_EVENT;

    startForeground(ContextConstants.LAUNCHER_SERVICE_NOTE_ID, note);

It always shows StartingActivity, the question is that how to call resuming activity when notification is clicked. If the activity has not already been destroyed and i can just call that instance back(resume it) and therefore not needing to load it again and won't need to add another activity to my stack. Is it possible?


回答1:


I find a solution like open recently activity in Notification:

NotificationManager nm = (NotificationManager) getSystemService(context.NOTIFICATION_SERVICE);
Notification notification = new Notification();
notification.flag = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;

Intent nIntent = new Intent();
nIntent = getPreviousIntent();

PendingIntent pi = PendingIntent.getActivity(this, 0, nIntent, 0);
notification.setLatestEventInfo(getContext(), "some Title", "some text", pi);
nm.notify(0,notification);

private Intent getPreviousIntent(Intent newIntent) {
    final ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    final List<ActivityManager.RecentTaskInfo> recentTaskInfos = am.getRecentTasks(1024,0);
    String myPkgNm = getPackageName();

    if (!recentTaskInfos.isEmpty()) {
        ActivityManager.RecentTaskInfo recentTaskInfo;
        for (int i = 0; i < recentTaskInfos.size(); i++) {
            recentTaskInfo = recentTaskInfos.get(i);
            if (recentTaskInfo.baseIntent.getComponent().getPackageName().equals(myPkgNm)) {
                newIntent = recentTaskInfo.baseIntent;
                newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
        }
    }
    return newIntent;
}

you have to add <uses-permission android:name="android.permission.GET_TASKS" />



来源:https://stackoverflow.com/questions/26904705/android-displaying-multiple-activity-in-saved-state-when-notification-click

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