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

后端 未结 5 848
北海茫月
北海茫月 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

    In fact to stopping the service we must use the method stopService() and you are doing in right way:

    Start service:

      Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
      startService(myService);
    

    Stop service:

      Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
      stopService(myService);
    

    if you call stopService(), then the method onDestroy() in the service is called (NOT the stopService() method):

      @Override
        public void onDestroy() {
          timer.cancel();
          task.cancel();    
            Log.i(TAG, "onCreate() , service stopped...");
        }
    

    you must implement the onDestroy() method!.

    Here is a complete example including how to start/stop the service.

提交回复
热议问题