how to prevent service to run again if already running android

Use startService(). Start Service will call onStartCommand() If the Service isn't started yet it will Call onCreate(). Initialize your variables and/or start a Thread in onCreate().


Bind your service; when starting call:

Intent bindIntent = new Intent(this,ServiceTask.class);
    startService(bindIntent);
    bindService(bindIntent,mConnection,0);

Then to check if your service is working, use a method like:

    public static boolean isServiceRunning(String serviceClassName){ 
             final ActivityManager activityManager = (ActivityManager)Application.getContext().getSystemService(Context.ACTIVITY_SERVICE);     
             final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);      
           for (RunningServiceInfo runningServiceInfo : services) {         
             if (runningServiceInfo.service.getClassName().equals(serviceClassName)){             
                return true;         
             }     
           }     
         return false; 
        }

A service will only run once, so you can call startService(Intent) multiple times.

You will receive an onStartCommand() in the service. So keep that in mind.

Source: Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

At: http://developer.android.com/reference/android/app/Service.html on topic: Service Lifecycle


Whenever we start any service from any activity , Android system calls the service's onStartCommand() method And If the service is not already running, the system first calls onCreate(), and then it calls onStartCommand().

So mean to say is that android service start's only once in its lifecycle and keep it running till stopped.if any other client want to start it again then only onStartCommand() method will invoked all the time.