stop IntentService from Activity

泪湿孤枕 提交于 2019-12-11 07:26:55

问题


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



来源:https://stackoverflow.com/questions/10362981/stop-intentservice-from-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!