Stopping an Android Service from within a thread

梦想与她 提交于 2019-12-22 06:44:38

问题


I have a Service which starts a thread during onCreate(). The thread is monitoring hardware (IOIO) and will end once it is disconnected so essesentially is an infinite loop. Stopping the service from an Activity works fine and the thread also stops (ended in onDestory()).

My problem is that if the thread dies (say because of an exception) is it possible to stop the service that spawned it.

I've tried using stopSelf() from within the thread code but the service does not stop.

Thank you ps my first post so please excuse any missing conventions I should have followed.


回答1:


I think what you want here might be to use a Handler. Eseentially, create a handler for your Sevrice (make sure it's final so you can use across all threads). Then in your other thread, call:

myServiceHandler.post(new Runnable(){
  public void run(){
    stopSelf();
  }
}



回答2:


How about storing the Intent of the service and stopping it directly? In the service:

private Intent thisIntent;

public int onStartCommand (Intent intent, int flags, int startId) {

    thisIntent = intent;

In the thread inside the service:

stopService(thisIntent);


来源:https://stackoverflow.com/questions/8052165/stopping-an-android-service-from-within-a-thread

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