stop IntentService from Activity

2019-08-06 06:17发布

问题:

I need help with this situation:

  1. I have activity, what starts IntentService.
  2. Service do some job in while cycle and sleep for some time.
  3. Main cycle of service is endless, so I need to stop it from activity again.
  4. I must be able to end activity, start it again and stop IntentService from new "instance" of activity.

    public class MyService extends IntentService {
    
        public MyService()
        {
            super("MyService");
        }
    
        public MyService(String name) {
            super(name);
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d("SERVICE", "start");
    
            while(true)
            {
                SystemClock.sleep(1000);
                Log.d("SERVICE", "tick");
            }
        }
    
        @Override
        public void onDestroy() {
            Log.d("SERVICE", "end");
            super.onDestroy();
        }
    

...

Intent intent = new Intent(getApplicationContext(), MyService.class);
startService(intent);       

I tried calling stopService(), but it's not working. Is there any solution how to do this? Thanks in advance.

回答1:

Service do some job in while cycle and sleep for some time.

IMHO, this is an inappropriate use of IntentService. Please create a regular Service, with your own background thread that you manage yourself.

Is there any solution how to do this?

Create a regular Service, with your own background thread that you manage yourself. For example, you could use a ScheduledExecutorService instead of your sleep() loop, using shutdown() or shutdownNow() in the service's onDestroy().