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

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

java - Press home button to stop service

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...