Java 覆盖后退按钮以充当主页按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2000102/
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-13 02:18:17  来源:igfitidea点击:

Override back button to act like home button

javaandroidoverridingandroid-buttonback

提问by bdls

On pressing the back button, I'd like my application to go into the stopped state, rather than the destroyed state.

在按下后退按钮时,我希望我的应用程序进入停止状态,而不是销毁状态。

In the Android docsit states:

在 Android文档中,它指出:

...not all activities have the behavior that they are destroyed when BACK is pressed. When the user starts playing music in the Music application and then presses BACK, the application overrides the normal back behavior, preventing the player activity from being destroyed, and continues playing music, even though its activity is no longer visible

...并非所有活动都具有在按下 BACK 时被销毁的行为。当用户在 Music 应用程序中开始播放音乐然后按 BACK 时,应用程序会覆盖正常的后退行为,防止播放器活动被破坏,并继续播放音乐,即使其活动不再可见

How do I replicate this functionality in my own application?

如何在我自己的应用程序中复制此功能?

I think there must be three possibilities...

我觉得应该有三种可能……

  1. Capture the back button press (as below) and then call whatever method(s) the home button calls.

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            Log.d(this.getClass().getName(), "back button pressed");
        }
        return super.onKeyDown(keyCode, event);
    }
    
  2. Capture the back button press and then spoof a home button press.

  3. Capture the back button press, then start an Activity of the home screen, effectively putting my application's Activity into the stopped state.

  1. 捕获后退按钮按下(如下所示),然后调用主页按钮调用的任何方法。

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            Log.d(this.getClass().getName(), "back button pressed");
        }
        return super.onKeyDown(keyCode, event);
    }
    
  2. 捕获后退按钮按下,然后欺骗主页按钮按下。

  3. 捕获后退按钮按下,然后启动主屏幕的 Activity,有效地将我的应用程序的 Activity 置于停止状态。

Edit:I know about services and am using one in the application to which this problem is related. This question is specifically about putting the Activity into the stopped state rather than the destroyed state on pressing the back button.

编辑:我了解服务,并且正在与此问题相关的应用程序中使用服务。这个问题特别是关于在按下后退按钮时将 Activity 置于停止状态而不是销毁状态。

采纳答案by Mirko N.

Most of the time you need to create a Serviceto perform something in the background, and your visible Activitysimply controls this Service. (I'm sure the Music player works in the same way, so the example in the docs seems a bit misleading.) If that's the case, then your Activitycan finishas usual and the Servicewill still be running.

大多数情况下,您需要创建一个Service来在后台执行某些操作,而您的 visibleActivity只是控制它Service。(我确定音乐播放器的工作方式相同,因此文档中的示例似乎有点误导。)如果是这种情况,那么您Activity可以finish照常Service运行,并且仍将运行。

A simpler approach is to capture the Backbutton press and call moveTaskToBack(true)as follows:

一种更简单的方法是捕获Back按钮按下并调用moveTaskToBack(true)如下:

// 2.0 and above
@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

// Before 2.0
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

I think the preferred option should be for an Activity to finish normally and be able to recreate itself e.g. reading the current state from a Service if needed. But moveTaskToBackcan be used as a quick alternative on occasion.

我认为首选的选项应该是让 Activity 正常完成并能够重新创建自己,例如,如果需要,从 Service 读取当前状态。但moveTaskToBack有时可以用作快速替代品。

NOTE: as pointed out by Dave below Android 2.0 introduced a new onBackPressedmethod, and these recommendationson how to handle the Back button.

注意:正如 Dave 所指出的,Android 2.0 下面引入了一种新onBackPressed方法,以及这些关于如何处理后退按钮的建议。

回答by Dave Webb

If you want to catch the Back Button have a look at this post on the Android Developer Blog. It covers the easier way to do this in Android 2.0 and the best way to do this for an application that runs on 1.x and 2.0.

如果您想查看返回按钮,请查看Android 开发人员博客上的这篇文章。它涵盖了在 Android 2.0 中执行此操作的更简单方法以及在 1.x 和 2.0 上运行的应用程序执行此操作的最佳方法。

However, if your Activity is Stopped it still may be killed depending on memory availability on the device. If you want a process to run with no UI you should create a Service. The documentation says the following about Services:

但是,如果您的 Activity 已停止,它仍可能会被终止,具体取决于设备上的内存可用性。如果您希望进程在没有 UI 的情况下运行,您应该创建一个Service. 文档说明了以下有关服务的内容:

A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it.

服务没有可视化用户界面,而是无限期地在后台运行。例如,服务可能会在用户处理其他事务时播放背景音乐,或者它可能会通过网络获取数据或计算某些内容并将结果提供给需要它的活动。

These seems appropriate for your requirements.

这些似乎适合您的要求。

回答by m-szalik

try to override void onBackPressed()defined in android.app.Activity class.

尝试覆盖onBackPressed()android.app.Activity 类中定义的void 。

回答by craigk

if it helps someone else, I had an activity with 2 layouts that I toggled on and off for visibilty, trying to emulate a kind of page1 > page2 structure. if they were on page 2 and pressed the back button I wanted them to go back to page 1, if they pressed the back button on page 1 it should still work as normal. Its pretty basic but it works

如果它对其他人有帮助,我有一个带有 2 个布局的活动,我为了可见性而打开和关闭这些布局,试图模拟一种 page1 > page2 结构。如果他们在第 2 页并按下后退按钮,我希望他们返回到第 1 页,如果他们按下第 1 页上的后退按钮,它应该仍然正常工作。它非常基本但有效

@Override
public void onBackPressed() {
// check if page 2 is open
    RelativeLayout page2layout = (RelativeLayout)findViewById(R.id.page2layout);
    if(page2layout.getVisibility() == View.VISIBLE){
        togglePageLayout(); // my method to toggle the views
        return;
    }else{
        super.onBackPressed(); // allows standard use of backbutton for page 1
    }

}

hope it helps someone, cheers

希望它可以帮助某人,欢呼

回答by Sameer Z.

I have use @Mirko N. answser using made the new Custom EditText

我已经使用@Mirko N. answser 使用了新的自定义 EditText

 public class EditViewCustom extends EditText {

    Button cancelBtn;
    RelativeLayout titleReleLayout;
    public EditViewCustom(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public EditViewCustom(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EditViewCustom(Context context) {
        super(context);
    }

    public void setViews(Button cancelBtn,RelativeLayout titleReleLayout){
        this.cancelBtn = cancelBtn;
        this.titleReleLayout = titleReleLayout;
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            Log.d("KEYCODE_BACK","KEYCODE_BACK");
            cancelBtn.setVisibility(View.GONE);
            this.setFocusableInTouchMode(false);
            this.setFocusable(false);
            titleReleLayout.setVisibility(View.VISIBLE);

            return super.onKeyPreIme(keyCode, event);
          }

        return super.onKeyPreIme(keyCode, event);
    }

}

Then set data from your activity

然后从您的活动中设置数据

 searchEditView.setViews(cancelBtn, titleRelativeLayout);

Thank you.

谢谢你。

回答by Aniruddh Ambarkar

Use the following code:

使用以下代码:

public void onBackPressed() {    
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    startActivity(intent);
}

回答by user1524315

Even better, how about OnPause():

更好的是,OnPause()怎么样:

Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume().

当活动进入后台但尚未(尚未)被终止时,作为活动生命周期的一部分被调用。对应于 onResume()。

When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure toenter code herenot do anything lengthy here.

当活动 B 在活动 A 之前启动时,将在 A 上调用此回调。在 A 的 onPause() 返回之前不会创建 B,因此请确保enter code here不要在这里做任何冗长的事情。

This callback is mostly used for saving any persistent state the activity is editing and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one.

此回调主要用于保存 Activity 正在编辑的任何持久状态,并确保在没有足够资源启动新 Activity 的情况下不会丢失任何内容,而无需先杀死该 Activity。

This is also a good place to do things like stop animations and other things that consume a noticeable amount of CPU in order to make the switch to the next activity as fast as possible, or to close resources that are exclusive access such as the camera.

这也是执行停止动画和其他消耗大量 CPU 以尽快切换到下一个活动或关闭独占访问的资源(例如相机)等操作的好地方。

回答by Jawad Zeb

Working example..

工作示例..

Make sure don't call super.onBackPressed();

确保不要调用 super.onBackPressed();

@Override
public void onBackPressed() {
   Log.d("CDA", "onBackPressed Called");
   Intent setIntent = new Intent(Intent.ACTION_MAIN);
   setIntent.addCategory(Intent.CATEGORY_HOME);
   setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(setIntent);
}

In this way your Back Button act like Home button . It doesn't finishes your activity but take it to background

通过这种方式,您的后退按钮就像主页按钮一样。它不会完成您的活动,而是将其带入后台

Second way is to call moveTaskToBack(true);in onBackPressedand be sure to remove super.onBackPressed

第二个方法是调用 moveTaskToBack(true);onBackPressed,一定要卸下super.onBackPressed

回答by SaiLiu

Override onBackPressed() after android 2.0. Such as

在 android 2.0 之后覆盖 onBackPressed()。如

@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

回答by ubulon

I've tried all the above solutions, but none of them worked for me. The following code helped me, when trying to return to MainActivity in a way that onCreate gets called:

我已经尝试了上述所有解决方案,但没有一个对我有用。在尝试以调用 onCreate 的方式返回 MainActivity 时,以下代码对我有所帮助:

Intent.FLAG_ACTIVITY_CLEAR_TOP is the key.

Intent.FLAG_ACTIVITY_CLEAR_TOP 是关键。

  @Override
  public void onBackPressed() {
      Intent intent = new Intent(this, MainActivity.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(intent);
  }