Android 单击启动器图标仅在从通知启动该 Activity 后发出时才会启动新 Activity

标签 android back-stack

通过单击启动器中的应用程序图标启动一个 Activity ,应该将该 Activity 带到前台,就像从历史记录中选择它一样。因此不应存在 onCreate 调用。

但是,如果我们在通过单击通知启动 Activity 后尝试执行此操作,则启动器只会启动 Activity 的另一个实例。

我必须添加什么标志才能使启动器继续按预期工作(从后台恢复应用程序的确切状态)?

我会发布基本代码。

这将启动通知:

Intent resumeIntent = new Intent(this, MainActivity.class);
PendingIntent resumePendingIntent = PendingIntent.getActivity(this, 2,
        resumeIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Notification resumeNotification = new Notification.Builder(this).setContentTitle(
        "Resume style")
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentIntent(resumePendingIntent)
        .build();

NotificationManager notificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
notificationManager.notify(1, launcherNotification);

这是 list Activity 的样子:

    <activity
        android:name="com.example.ihatenotifiicationsapp.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

此resumeIntent 将由Android 自动添加到FLAG_ACTIVITY_NEW_TASK。此标志将允许从后台恢复应用程序(如果存在)。

到这里为止一切都很好,但是,如果在您单击此通知并恢复该应用程序后,您从启动器中单击该应用程序,然后 Android 将启动 MainActivity 的另一个实例。

这会破坏我的应用程序和后台堆栈(您将在堆栈中有 2 个 MainActivity,这对用户来说很奇怪)。

有趣的是只有在您单击通知后才会发生这种情况(单击启动器行为以启动另一个实例)。

最佳答案

如果您想要这种行为,您可以在 activity 标记中使用标记 android:launchMode="singleTask"。如果当前有一个 Activity 实例,这将阻止操作系统启动任何其他实例。有关启动行为的更多信息,请参阅 SDK Doku here

我根据下面的 Emanuel Moecklin 评论编辑了这个答案。混合了 lauchModes。

摘自独库:

The system creates the activity at the root of a new task and routes the intent to it. However, if an instance of the activity already exists, the system routes the intent to existing instance through a call to its onNewIntent() method, rather than creating a new one.

关于Android 单击启动器图标仅在从通知启动该 Activity 后发出时才会启动新 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19518296/

相关文章:

android - 实现 "UP"按钮功能

android - android studio NDK 上的 turbo c++ graphics.h 程序

android - 为什么 AudioManager.getRingerMode() 只返回 3 种模式?

android - 如何在 Android 中将 Fragments 添加到后台堆栈

Android 运行时权限完成调用 Activity

android - 如何像启动画面一样只运行一次 Activity

android - 在android中操作任务返回栈

android - 在 Eclipse 中调试时即时查看 Canvas /位图

android - 使用简单日期格式解析日期时出现空指针异常

android - 如何在 android 中包含如下图所示的平方根符号?