Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Activity is started in Service

Tags:

java

android

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!!

like image 717
user584513 Avatar asked Nov 05 '22 02:11

user584513


1 Answers

You should change the launchMode of your activity to singleTask in the androidManifest.xml file.

The default value for this property is standard, which allows any number of instances to run.

"singleTask" and "singleInstance" activities can only begin a task. 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. 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. 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.

Check out the Android Developers' Guide for a more detailed explanation (the quote is from there as well)

<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>
like image 82
rekaszeru Avatar answered Nov 13 '22 03:11

rekaszeru