How to call stopservice() method of Service class from the calling activity class

后端 未结 5 850
北海茫月
北海茫月 2020-11-30 06:19

I am trying to call my service class\'s stopService() method from my activity. But I dont know how to access stopservice method from my activity class. I have the below code

5条回答
  •  旧巷少年郎
    2020-11-30 06:48

    That looks like it should stop the service when you uncheck the checkbox. Are there any exceptions in the log? stopService returns a boolean indicating whether or not it was able to stop the service.

    If you are starting your service by Intents, then you may want to extend IntentService instead of Service. That class will stop the service on its own when it has no more work to do.

    AutoService

    class AutoService extends IntentService {
         private static final String TAG = "AutoService";
         private Timer timer;    
         private TimerTask task;
    
         public onCreate() {
              timer = new Timer();
              timer = new TimerTask() {
                public void run() 
                {
                    System.out.println("done");
                }
              }
         }
    
         protected void onHandleIntent(Intent i) {
            Log.d(TAG, "onHandleIntent");     
    
            int delay = 5000; // delay for 5 sec.
            int period = 5000; // repeat every sec.
    
    
            timer.scheduleAtFixedRate(timerTask, delay, period);
         }
    
         public boolean stopService(Intent name) {
            // TODO Auto-generated method stub
            timer.cancel();
            task.cancel();
            return super.stopService(name);
        }
    
    }
    

提交回复
热议问题