Android Background Service Template

  Uncategorized

This is a simple Android background Service Template. You can use it to run updates in the background without blocking the UI. To start and stop the service use the following lines in your activity:

// starting the service
Intent intent = new Intent(this, UpdateService .class);
startService(intent);
// stopping the service
Intent intent = new Intent(this, UpdateService .class);
stopService(intent);
// The UpdateService class 
// Change the interval integer value to your needs and implement the UpdateThread.run method with your requrements

public class UpdateService extends Service 
{
    private UpdateThread myythread;
    public Intent intent;
    public boolean isRunning = false;

    long interval=30000; // Fixed interval of 30 seconds

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

    @Override
    public void onCreate() 
    {
        super.onCreate();
        myythread  = new UpdateThread(interval);
    }

    @Override
    public synchronized void onDestroy() 
    {
        super.onDestroy();

        if(!isRunning)
        {
            myythread.interrupt();
            isRunning = false;
        }
    }

    @Override
    public synchronized void onStart(Intent intent, int startId) 
    {
        super.onStart(intent, startId);

        if(!isRunning)
        {
            myythread.start();
            isRunning = true;
        }
    }

    class UpdateThread extends Thread
    {
        long interval;
        public UpdateThread(long interval)
        {
            this.interval=interval;
        }

        @Override
        public void run()
        {
            while(isRunning)
            {
                System.out.println("Service running");
                try 
                {
                	 // TODO Service actions
                     Thread.sleep(interval);
                } 
                catch (InterruptedException e) 
                {
                    isRunning = false;
                }
            }
        }
    }
}

This is all you need to execute a service on android devices. Don’t forget to add the service to your AndroidManifest.xml file.