android - onStart 调用两次,中间没有 onStop?

标签 android android-activity android-lifecycle android-pendingintent

我有一个已经可见的 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/

相关文章:

java - Android - 打开已经创建的 Activity

Android 服务仅在 UI 处于 Activity 状态时运行

java - 如何扩展 ListActivity where AppCompatActivity in Android Activity

android - 以编程方式使用命令将应用程序包制作为设备所有者

Android httpclient - 获取具有抢先身份验证的文件

android - Cordova:应用程序在使用相机后重新启动

java - 从 android 中的 Activity X 启动 Activity X

java - Android - 在 Fragment 类中保存成员字段的值

android - 在屏幕旋转时在 ViewPager 中显示带有数据的 fragment

java - 是否可以设置一个计时器来显示/隐藏 Material 设计中的密码?