防止后退按钮关闭我的应用程序
我在应用程序的活动中使用以下代码来防止它关闭我的应用程序。
/* Prevent app from being killed on back */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Back?
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Back
moveTaskToBack(true);
}
// Return
return super.onKeyDown(keyCode, event);
}
它不起作用。该应用程序设置为兼容 Android 1.6(API 级别 4)。单击我的应用程序图标会在 Splash 活动(这是主活动)中重新启动我的应用程序。如何防止我的应用程序关闭?
I am using the following code in my application's activity to prevent it from closing my app on back.
/* Prevent app from being killed on back */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Back?
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Back
moveTaskToBack(true);
}
// Return
return super.onKeyDown(keyCode, event);
}
It does not work. The app is set to be Android 1.6 (API Level 4) compatible. Clicking on my application icon restarts my app at a Splash activity (which is the Main). How can I prevent my app from closing on back?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更简洁的解决方案:-
A more succinct solution:-
您是否尝试过将
super
调用放在 else 块中,以便仅在键不是KEYCODE_BACK
时才调用它?但老实说,您不能依赖这一点,因为一旦您的应用程序被置于后台,系统随时可以回收它以回收内存。
Have you tried putting the
super
call in an else block so it is only called if the key is notKEYCODE_BACK
?In all honesty though, you can't rely on this because once your app is placed in the background, at any moment it could be recycled for the system to reclaim memory.
即使你可以这样做,你也不应该这样做。强制用户始终将您的应用程序保留在内存中并不是一个好主意,而且只会惹恼他们。
Even if you could do that, you should not. Enforcing users to keep your app in the memory all the time is not a good idea and will only annoy them.
如果需要向后导航并防止关闭,则在 Android WebView 中使用:
If need to navigate back as well as preventing from closing, then in Android WebView use this: