问题
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