Unfortunately, this is a difficult issue due to how Android works. There are a number of strategies, each of which relates to different parts of the problem. Combine several strategies for best results.
Please note that some of these strategies are no longer needed in later versions of Android.
1. Run the action
What to do
Taken from the Foreground Service, killed when receiving a broadcast after acitivty waved off the task list :
In the foreground:
@Override public void onTaskRemoved( Intent rootIntent ) { Intent intent = new Intent( this, DummyActivity.class ); intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); startActivity( intent ); }
In the manifest:
<activity android:name=".DummyActivity" android:theme="@android:style/Theme.NoDisplay" android:enabled="true" android:allowTaskReparenting="true" android:noHistory="true" android:excludeFromRecents="true" android:alwaysRetainTaskState="false" android:stateNotNeeded="true" android:clearTaskOnLaunch="true" android:finishOnTaskLaunch="true" />
(If your service is in a different process, set this activity process to the same.)
In DummyActivity.java:
public class DummyActivity extends Activity { @Override public void onCreate( Bundle icicle ) { super.onCreate( icicle ); finish(); } }
Side effects
Causes retentate activity to close. Normally disabling the application does not close the repetition activity.
disadvantages
It takes effect when fictitious activity begins , which can take half a second or more, so this still leaves the service open in order to be killed a bit.
Explanation
When you uninstall / delete your application, set the waitingToKill flag. While this flag is set, Android can kill the process at any time in the future , for example, when receiving a broadcast . The start of an action clears this flag.
What to do
Combine this in your utility code:
if (Build.VERSION.SDK_INT >= 16) { Intent intent = new Intent(this, DummyReceiver.class); intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Create a dummy broadcast receiver:
public class DummyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {} }
Add the recipient to your manifest:
<receiver android:name=".DummyReceiver" />
Side effects
May cause a slight delay (~ 250 ms) / freeze when a task is removed from the repeat screen.
disadvantages
This only keeps working in the process of receiving broadcasts. the waitingToKill flag is still set , so after that the process can be killed, for example, when the broadcast is received.
Explanation
If your process does not work in foreground priority, Android will try to kill it immediately . Receiving broadcast broadcasts in the foreground temporarily prevents this, as a result of which the waitingToKill flag is set waitingToKill .
3. Do not get attached to services
Service binding seems to increase the likelihood that the service process will be destroyed immediately when the task is deleted.