how to prevent service to run again if already running android

前端 未结 5 2132
猫巷女王i
猫巷女王i 2021-02-06 21:49

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

相关标签:
5条回答
  • 2021-02-06 22:08

    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.

    0 讨论(0)
  • 2021-02-06 22:13

    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

    0 讨论(0)
  • 2021-02-06 22:14

    So, for avoiding restarting a task again and again, You can use boolean values, that the task is already started or ongoing. Put the method both in oncreate and onstartCommand, and checked with the boolean:

     boolean isTimerTaskRunning = false;
    private boolean isServiceKeepRunning(){
            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
            return settings.getBoolean("silentModeKeepRunning", true);
        }
    
    @Override
        public void onCreate() {
            super.onCreate();
            Log.i(TAG, "onCreate: Called");
            Log.i(TAG, "onCreate: keepRunning "+isServiceKeepRunning());
            if(!isTimerTaskRunning) {
                startTimerTask();
                isTimerTaskRunning = true;
            }
            //startForeground(REQUEST_CODE /* ID of notification */, notificationbuilder().build());
    
        }
    
     @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            localData = new LocalData(this);
          //  return super.onStartCommand(intent, flags, startId);
            Log.i(TAG, "onStartCommand: Called");
            Log.i(TAG, "onStartCommand: keepRunning "+isServiceKeepRunning());
    
            Toast.makeText(this, "This is The Mode For Silent. ", Toast.LENGTH_LONG).show();
    
            if(!isTimerTaskRunning) {
                Log.i(TAG, "TimerTask was not Running - started from onStartCommand");
               startTimerTask();
               isTimerTaskRunning = true;
    
            }else {
                Log.i(TAG, "TimerTask was already Running - checked from onStartCommand");
    
            }
            //return START_REDELIVER_INTENT;
            startForeground(REQUEST_CODE /* ID of notification */, notificationbuilder().build());
    
            return  START_STICKY;
    }
    
    0 讨论(0)
  • 2021-02-06 22:15

    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; 
            }
    
    0 讨论(0)
  • 2021-02-06 22:26

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

    0 讨论(0)
提交回复
热议问题