Android:从通知中恢复上次活动

Giu*_*ppe 4 android

我的目标是,如果用户点击通知,则返回上一个活动.我以这种方式在服务onCreate()中创建通知:

Intent notificationIntent = new Intent(this, MainActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Run Code Online (Sandbox Code Playgroud)

但是当我点击通知时,这将转到MainActivity而不是之前打开的最后一个单击主页按钮.

在清单中,我尝试使用launchMode ="singleTop","standard"和"singletask"来使用MainActivity,但没有成功.

谢谢.

Pra*_*abu 6

只需使用Android启动应用时使用的相同意图过滤器:

    final Intent notificationIntent = new Intent(context, YourActivity.class);
    notificationIntent.setAction(Intent.ACTION_MAIN);
    notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
Run Code Online (Sandbox Code Playgroud)

由于您从通知栏打开活动所创建的意图与用于启动应用程序的Android相同,因此将显示先前打开的活动而不是创建新活动.


Vik*_*mar 5

使用以下代码..

 contentTitle = "MyApp";
    contentText = "Reopen App";
notificationIntent = new Intent(this, MainActivity.class);
    contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(getApplicationContext(), contentTitle, contentText, contentIntent);
Run Code Online (Sandbox Code Playgroud)

并在Android Manifest中将Activity设置为SingleTop或SingleInstance,然后重新打开仍处于活动状态的活动,而不是创建新活动.