Search This Blog

Saturday, 4 May 2013

How to make Android service unstoppable and run it continuously

Android service runs in different mode with help of flag e.g START_CONTINUATION_MASK, START_NOT_STICKY. It enable to control the behavior of Android service life. But service will work until user allow it work. If he/she stops it, it will destroy automatically. More than often, we required it to run unstoppable  If in case user stop, re-instance the old service instance.
For some people, it may malware but sometimes we have to full filled client requirement and that's all our purpose is.

Case when your service can be stopped

  • User stop it forcefully
  • Low Memory situation
  • Device restarted

Handling first two case

When ever we stop service forcefully (or os kill it), it will call onDestory() method. First concept is to use one receiver and send one broadcast whenever service destroy. And restarted service again.

Third case if device is restarted then already we had onBootCompleted action for receiver to catch

Lets go steps by Step to make our Android Service unstoppable

Step 1) Create one Android BroadCastReciever and register it for two action


        <service android:name="ServiceTest" >

        <receiver android:name="ReceiverCall" >
                <action android:name="" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
        </receiver> is the custom action. BroadCastReceiver Class contain code to restart service again

public class ReceiverCall extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        Log.i("Service Stops", "Ohhhhhhh");
        context.startService(new Intent(context, ServiceTest.class));;


Step 2) Create Android service class , do some task there (I have taken one Timer to print Log) and in onDestory()

    public void onDestroy() {
        try {
        } catch (Exception e) {
        Intent intent = new Intent("");
        intent.putExtra("yourvalue", "torestore");

Run your application and go to setting, See running service, you will TestService. Try to close it , ohhhhhh it will not close.

DownloadSource Application

Android News and source code