简体   繁体   English

检查Activity是否在Service中启动

[英]Check if Activity is started in Service

I have a service that is doing some background staff, then I need to start a Activity showing some results that the Service processed. 我有一个服务,正在做一些后台工作人员,然后我需要启动一个活动,显示服务处理的一些结果。 But there is possibility that the activity is started many times from the service. 但是有可能从服务开始多次活动。 Now, I want to start this Activity only if it is not active already. 现在,我想只在它尚未激活时启动此活动。

What is the possibility and how to do this? 有什么可能性以及如何做到这一点? And sample code would be nice if you don't mind. 如果你不介意的话,示例代码会很好。

Thanks!! 谢谢!!

You should change the launchMode of your activity to singleTask in the androidManifest.xml file. 您应该改变launchMode你的活动,以singleTask在AndroidManifest.xml文件。

The default value for this property is standard , which allows any number of instances to run. 此属性的默认值为standard ,允许运行任意数量的实例。

"singleTask" and "singleInstance" activities can only begin a task. “singleTask”和“singleInstance”活动只能开始一项任务。 They are always at the root of the activity stack. 它们始终位于活动堆栈的根部。 Moreover, the device can hold only one instance of the activity at a time — only one such task. 此外,设备一次只能保存一个活动实例 - 只有一个这样的任务。 [...] [...]

The "singleTask" and "singleInstance" modes also differ from each other in only one respect: A "singleTask" activity allows other activities to be part of its task. “singleTask”和“singleInstance”模式在一个方面也各不相同:“singleTask”活动允许其他活动成为其任务的一部分。 It's always at the root of its task, but other activities (necessarily "standard" and "singleTop" activities) can be launched into that task. 它始终是其任务的根源,但其他活动(必然是“标准”和“单一活动”)可以启动到该任务中。 A "singleInstance" activity, on the other hand, permits no other activities to be part of its task. 另一方面,“singleInstance”活动不允许其他活动成为其任务的一部分。 It's the only activity in the task. 这是任务中唯一的活动。 If it starts another activity, that activity is assigned to a different task — as if FLAG_ACTIVITY_NEW_TASK was in the intent. 如果它启动另一个活动,则该活动将分配给另一个任务 - 就像FLAG_ACTIVITY_NEW_TASK在意图中一样。

Check out the Android Developers' Guide for a more detailed explanation (the quote is from there as well) 查看Android开发人员指南以获取更详细的说明(报价也来自那里)

<activity android:name=".activity.YourActivity" 
    android:launchMode="singleTask"
    android:alwaysRetainTaskState="true"
    android:clearTaskOnLaunch="false" 
    android:finishOnTaskLaunch="false">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM