按主页按钮停止服务 [英] Press home button to stop service

查看:89
本文介绍了按主页按钮停止服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想如果用户按下主页按钮我的服务将停止,这是我的代码,但它不适合我,请帮助我:

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);
}

谢谢

推荐答案

如果您正在尝试确保服务仅在相关活动可见时运行,则更好的解决方案是在onPause()方法中停止服务,无论用户是什么活动运行。这样,当用户按下返回并且用户按下主页时处理事件。

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.

这篇关于按主页按钮停止服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆