如果一个 activity 是由监听器创建的,然后监听器被销毁,任务会发生什么?

If an activity is created by a listener, then the listener is destroyed, what happens to the task?

我有一个 Android wear class,它扩展了 WearableListenerService 并且正在创建一个 activity。文档说明了创建 activity:

时的活动和任务

A new activity is, by default, launched into the task of the activity that called startActivity().

因此我的 activity 被添加到 WearableListenerService 任务中。

我无法控制 WearableListenerService 的生命周期 - 只要手机向可穿戴设备发送消息,OS 就会调用其 onCreate() 和 onDestroy() 方法。

我的问题是在这种情况下会发生什么:

1) WearableListenerService onCreate() gets called
2) WearableListenerService onMessageReceived() gets called and the WearableListenerService starts a new activity
3) WearableListenerService onDestroy() gets called, but the activity is still present
4) WearableListenerService onCreate() gets called again
5) WearableListenerService onMessageReceived() gets called again and the activity is started agai

n.

在 5),如果 2) 中的 activity 仍然存在,那么我不想创建一个新的单独的 activity,我总是想要一个单例 activity。

通常我可以使用FLAG_ACTIVITY_CLEAR_TOP、FLAG_ACTIVITY_SINGLE_TOP等。 然而,由于 WearableListenerService onDestroy() 在阶段 3) 被调用,这是否意味着在阶段 4) 创建了一个新任务,因此这些标志无效?

我该如何进行试验?有没有一种程序化的方法可以找出 activity 所在的任务的名称?

However as WearableListenerService onDestroy() got called at stage 3) does this mean a new task gets created at stage 4) and thus these flags have no effect?

如果您正在使用,android:launchMode="singleTop"

然后如果 activity 的实例已经存在于当前任务的顶部并且系统将意图路由到此 activity,则不会创建新实例,因为它会触发 onNewIntent() 方法而不是创建一个新对象。

因此请检查 Activity 中的 onNewIntent() 方法。

更具体地说,如果您的应用程序没有任何实例 运行,则您的应用程序任务只会被销毁或清除,任何 Activity 或服务或系统在低内存情况下都需要内存。

同样,您也可以使用 android:launchMode="singleTask" 在单独的任务中启动 Activity。所以你的 activity 总是从新任务开始,并与 singleTop 结合总是保持在顶部,这样你就可以从它以前的状态恢复而不是重新创建它。