how to prevent service to run again if already running android

前端 未结 5 2138
猫巷女王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: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 services = activityManager.getRunningServices(Integer.MAX_VALUE);      
               for (RunningServiceInfo runningServiceInfo : services) {         
                 if (runningServiceInfo.service.getClassName().equals(serviceClassName)){             
                    return true;         
                 }     
               }     
             return false; 
            }
    

提交回复
热议问题