how to prevent service to run again if already run

2019-03-17 03:39发布

问题:

On click of a button I want to start service using method startService(new Intent(currentActivity.this,MyService.class)) but if service is running I don't want to call this method to avoid run service that is already running.How this is possible.I am using both Intent service and Service in same project and want to apply same condition for both.

回答1:

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



回答2:

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().



回答3:

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; 
        }


回答4:

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.