onStart调用了两次,其间没有onStop?

时间:2015-01-25 07:40:06

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

我有一个已经可见的活动(所以onStart已经运行),我拉下通知栏,点击与所述活动的待处理意图相关的通知。 1)onPause被调用。请注意,不会调用onStop 2)onCreate为活动的新实例调用然后onStart等...

正如我所建议的那样,我尝试过singleTask和singleInstance但它们并不会阻止在调用onPause之后创建一个新实例。有趣的是,只有当活动可见并且我点击其通知时才会发生这种情况。如果它已经停止,Android将使用旧实例。也许我需要调整PendingIntent的生成方式......

1 个答案:

答案 0 :(得分:2)

我认为在运行Pending Intent时,可能会在堆栈中创建一个新的Activity。配置您的活动,以便它不会通过设置为singleTask或singleInstance的launchMode创建新的Activity。

以下是我用于活动的设置示例:

<activity
            android:name="com.zakimak.HomeScreenActivity"
            android:screenOrientation="portrait"
            android:label="@string/app_name"
            android:launchMode="singleTask" />

然后构建待定意图如下:

    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是因为在抽屉下仍然可以看到活动。

步骤2:启动应用程序并显示HomeScreenActivity并按Home或启动另一个活动,然后调用onStop。然后我拖动通知栏并单击通知。它打开Activity并调用以下回调方法:onStart,然后是onResume。

在两种情况下,onCreate只调用一次,当第一次迭代启动Activity时。它在模拟器中进行了测试。

在某些情况下,当您的设备负载过重或试图节省电量时,Android可能会终止该过程。