0

我的应用上有通知。它在前台工作得很好。当我在其他活动中并按下主页按钮后,我单击通知。它打开给定的活动,但我需要在保存状态下显示以前的活动。

        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);

它总是显示StartingActivity,问题是单击通知时如何调用恢复活动。如果活动尚未被销毁,我可以只调用该实例(恢复它),因此不需要再次加载它,也不需要向我的堆栈添加另一个活动。可能吗?

4

1 回答 1

1

我在通知中找到了类似打开最近活动的解决方案:

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;
}

你必须添加<uses-permission android:name="android.permission.GET_TASKS" />

于 2014-11-14T08:59:49.587 回答