Activity 通过 PendingIntent 调用自动销毁

Activity called via PendingIntent getting destroyed automatically

我有一个 Activity,清单中设置了以下特殊属性

<activity
        android:name=".LightUp"
        android:excludeFromRecents="true"
        android:launchMode="singleInstance"
        android:noHistory="true"
        android:process=":listener"
        android:taskAffinity="" >
    </activity>

在这个 activity 中,我正在安排一个 AlarmManager 来使用这个 PendingIntent 在一段时间后调用它自己。 AlarmManager 是必需的,因为 phone 会在 activity 出现在屏幕上时进入睡眠状态,我不想保持唤醒锁。

pendingIntent = PendingIntent.getActivity(this, 10,
                new Intent(this, LightUp.class)
                .setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
                PendingIntent.FLAG_UPDATE_CURRENT);

所以当警报管理器触发时,我像往常一样在 onNewIntent() 函数中获取新的 Intent。这意味着意图一致 activity。 问题是 activity 在 onNewIntent 之后被销毁。即使我在 onNewIntent 中完全没有代码,我也可以从日志中看到 onDestroy 无论如何都会被调用。

所以问题是为什么要调用 Destroy?我该怎么做才能保留 activity 运行?

试试这个

Activity 清单

<activity
  android:name=".LightUp"
  android:launchMode="singleTop"
</activity>

Java代码

Intent notificationintent = new Intent(context, LightUp.class);
notificationintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationintent, PendingIntent.FLAG_UPDATE_CURRENT);

@Override
protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  System.out.println("new intent received");
  // do what ever you want to do here
}

试试这个:-

<activity
    android:launchMode="singleTask" >
</activity>

默认情况下,如果您调用带有意图的 activity,将创建并显示该 activity 的新实例,即使另一个实例已经是 运行。为避免这种情况,必须标记 activity,它不应被多次实例化。为此,您必须将 activity 的启动模式设置为 singleTask

看来我找到了罪魁祸首。这是导致问题的 noHistory 属性。 官方文档说

android:noHistory :: activity 是否应该从 activity 堆栈中移除并且当用户离开它并且它在屏幕上不再可见时完成(它的 finish() 方法被调用)

好吧,从技术上讲,我在调用 PendingIntent 时并没有离开屏幕,奇怪的是调用了 finish。删除 noHistory 后,它并没有破坏。