Creating Background Service in Android

Here is a semi-different way to keep the service going forever. There is ways to kill it in code if you’d wish

Background Service:

package com.ex.ample;

import android.app.Service;
import android.content.*;
import android.os.*;
import android.widget.Toast;

public class BackgroundService extends Service {

    public Context context = this;
    public Handler handler = null;
    public static Runnable runnable = null;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();

        handler = new Handler();
        runnable = new Runnable() {
            public void run() {
                Toast.makeText(context, "Service is still running", Toast.LENGTH_LONG).show();
                handler.postDelayed(runnable, 10000);
            }
        };

        handler.postDelayed(runnable, 15000);
    }

    @Override
    public void onDestroy() {
        /* IF YOU WANT THIS SERVICE KILLED WITH THE APP THEN UNCOMMENT THE FOLLOWING LINE */
        //handler.removeCallbacks(runnable);
        Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
    }
}

Here is how you start it from your main activity or wherever you wish:

startService(new Intent(this, BackgroundService.class));

onDestroy() will get called when the application gets closed or killed but the runnable just starts it right back up. You need to remove the handler callbacks as well.

I hope this helps someone out.

The reason why some people do this is because of corporate applications where in some instances the users/employees must not be able to stop certain things 🙂

http://i.imgur.com/1vCnYJW.png

Leave a Comment