我有一个已经可见的 Activity (因此 onStart 已运行),我拉下通知栏,单击与该 Activity 的待定 Intent 关联的通知。 1) onPause 被调用。请注意,不会调用 onStop 2) 为 Activity 的新实例调用 onCreate,然后调用 onStart,等等...
正如我所建议的那样,我尝试了 singleTask 和 singleInstance,但它们不会阻止在调用 onPause 后创建新实例。有趣的是,这仅在 Activity 可见并且我单击其通知时才会发生。如果它已经停止,Android 将使用旧实例。也许我需要调整 PendingIntent 的生成方式...
最佳答案
我认为当您运行 Pending Intent 时,可能会在堆栈中创建一个新的 Activity。配置您的 Activity,使其不会通过将 launchMode 设置为 singleTask 或 singleInstance 创建新的 Activity。
这是我用于 Activity 的设置示例:
<activity
android:name="com.zakimak.HomeScreenActivity"
android:screenOrientation="portrait"
android:label="@string/app_name"
android:launchMode="singleTask" />
然后构建pending intent如下:
Intent resultIntent = new Intent(context, HomeScreenActivity.class);
// The request code 24601 uniquely identifies the notification generated
// by the application. As an application may generate several having
//different codes to identify each. CAUTION: It's value should be greater than 0
//.i.e. RESULT_FIRST_USER+
PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
24601, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher).setContentTitle("Title")
.setContentText("Bla bla").setOngoing(true)
.setTicker("Bla bla is running").setAutoCancel(false)
.setContentIntent(resultPendingIntent).build();
第 1 步:我启动应用程序并显示 HomeScreenActivity。然后我拖动通知栏并单击通知。它打开 Activity 并调用以下回调方法:onPause,然后是 onResume。 onPause 被调用是因为 Activity 在抽屉下仍然可见。
第 2 步:我启动应用程序并显示 HomeScreenActivity 并按下 Home 或启动另一个 Activity ,然后调用 onStop。然后我拖动通知栏并单击通知。它打开 Activity 并调用以下回调方法:onStart 和 onResume。
在这两种情况下,当 Activity 为第一次迭代启动时,onCreate 仅被调用一次。它在模拟器中进行了测试。
在某些情况下,当您的设备负载很重或试图省电时,Android 可能会终止该进程。
关于android - onStart 调用两次,中间没有 onStop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28134291/