Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

i want to if the user press home button my service will be stop , this is my code but it's not working for me, please help me:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_HOME) {
stopService(new Intent(this, MyService.class));
return true;
}
return super.onKeyDown(keyCode, event);
}

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
706 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you're trying to make sure the service only runs when the related activity is visible, a better solution would be to stop the service in the onPause() method of whatever activity the user is running. That way, the event is handled when the user presses "back" and when the user presses "home".

Likewise, you can bind your service to the activity (or activities). The bound service will be destroyed when all activities bound to it stop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...