如何在android中捕获设备后退按钮事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11265490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:35:10  来源:igfitidea点击:

How to catch device back button event in android?

android

提问by SuReSh PaTi

I have open pdf file through my application.when click on device back button it is automatically come back to my application .It is working fine.Here i want catch back button event in device.I override the back button.but it is not working.please help me.

我已经通过我的应用程序打开了 pdf 文件。当点击设备返回按钮时,它会自动返回到我的应用程序。它工作正常。这里我想在设备中捕获返回按钮事件。我覆盖后退按钮。但它不起作用。请帮我。

回答by Stefano Ortisi

This is an example of what you are asking:

这是您要问的示例:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK ) {
        //do your stuff
    }
    return super.onKeyDown(keyCode, event);
}

回答by coading fever

just call the foolowing function this will close current activity and move you to the previous screen

只需调用傻瓜函数,这将关闭当前活动并将您移至上一个屏幕

finish();

回答by Dhaval

public void onBackPressed() {

        Intent intent = new Intent(CurrentActivity.this,
                PreviousActivity.class);
        startActivity(intent);

            return;
        }

回答by Narendra

If you have handled pdf file related operations(like reading etc) in your application i.e. there is Activity or Fragment handling this pdf file operations in your application then you can overrided onBackPressed() method to put your logic there. But if you are opening pdf via intent i.e using other application using intents action parameter then you can not overrided there onBackPressed() or onKeyDown() event in your application. But instead of that you can put your logic inside overriding onActivityResult() method in your activity from which you are opening the pdf file.

如果您在您的应用程序中处理了 pdf 文件相关操作(如阅读等),即在您的应用程序中有 Activity 或 Fragment 处理此 pdf 文件操作,那么您可以覆盖 onBackPressed() 方法将您的逻辑放在那里。但是,如果您通过意图打开 pdf,即使用其他应用程序使用意图操作参数,那么您不能在您的应用程序中覆盖 onBackPressed() 或 onKeyDown() 事件。但是,您可以将您的逻辑放在您打开 pdf 文件的活动中覆盖 onActivityResult() 方法中。

回答by MattC

You would override the onKeyDownevent in your Activity class and look for the keyCode of KEYCODE_BACK. To prevent further propagation you would return trueto stop the system from handling it and this should stop the back button from taking your user out of wherever you are.

您将覆盖Activity 类中的onKeyDown事件并查找KEYCODE_BACK的 keyCode 。为了防止进一步传播,您将返回true以阻止系统处理它,这应该阻止后退按钮将您的用户带出您所在的任何地方。

This violates the rules of what a user expects to happen, though, and is not recommended unless you're overriding the back button for something like going back through pages in a WebView or something like that.

但是,这违反了用户期望发生的规则,除非您为了返回 WebView 中的页面或类似内容而覆盖后退按钮,否则不建议这样做。