Android - 如何覆盖“后退”按钮使其不完成()我的活动?

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

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

androidandroid-activitynullpointerexceptionback-buttononkeypress

提问by Donal Rafferty

I currently have an Activity that when it gets displayed a Notification will also get displayed in the Notification bar.

我目前有一个活动,当它显示时,通知也将显示在通知栏中。

This is so that when the User presses home and the Activity gets pushed to the background they can get back to the Activity via the Notification.

这样当用户按下 home 键并且 Activity 被推到后台时,他们可以通过通知返回到 Activity。

The problem arises when a User presses the back button, my Activity gets destroyed but the Notification remains as I want the user to be able to press back but still be able to get to the Activity via the Notification. But when a USER tries this I get Null Pointers as its trying to start a new activity rather than bringing back the old one.

当用户按下后退按钮时会出现问题,我的活动被销毁但通知仍然存在,因为我希望用户能够按下后退但仍然能够通过通知到达活动。但是当用户尝试这个时,我得到空指针,因为它试图开始一个新的活动而不是带回旧的活动。

So essentially I want the Back button to act the exact same as the Home button and here is how I have tried so far:

所以基本上我希望返回按钮的行为与主页按钮完全相同,这是我到目前为止的尝试方式:



        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event)  {
            if (Integer.parseInt(android.os.Build.VERSION.SDK) < 5
                    && keyCode == KeyEvent.KEYCODE_BACK
                    && event.getRepeatCount() == 0) {
                Log.d("CDA", "onKeyDown Called");
                onBackPressed();
            }

            return super.onKeyDown(keyCode, event);
        }

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

            return;
        }   


However the above code still seems to allow my Activity to be destroyed, How can I stop my Activity from being destroyed when the back button is pressed?

然而,上面的代码似乎仍然允许我的 Activity 被销毁,如何在按下后退按钮时阻止我的 Activity 被销毁?

回答by ekawas

Remove your key listener or return truewhen you have KEY_BACK.

删除您的关键侦听器或true在您拥有KEY_BACK.

You just need the following to catch the back key (Make sure not to call superin onBackPressed()).

您只需要以下内容来获取返回键(确保不要调用superin onBackPressed())。

Also, if you plan on having a service run in the background, make sure to look at startForeground()and make sure to have an ongoing notification or else Android will kill your service if it needs to free memory.

此外,如果您计划在后台运行服务,请务必查看startForeground()并确保有持续的通知,否则 Android 会在需要释放内存时终止您的服务。

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

回答by Teo Inke

It was easier to implement it only with one line of code:

只用一行代码更容易实现它:

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

回答by kiswa

I think what you want is not to override the back button (that just doesn't seem like a good idea - Android OS defines that behavior, why change it?), but to use the Activity Lifecycleand persist your settings/data in the onSaveInstanceState(Bundle)event.

我认为您想要的不是覆盖后退按钮(这似乎不是一个好主意 - Android 操作系统定义了该行为,为什么要更改它?),而是使用Activity Lifecycle并将您的设置/数据保存在onSaveInstanceState(Bundle)事件。

@Override
onSaveInstanceState(Bundle frozenState) {
    frozenState.putSerializable("object_key",
        someSerializableClassYouWantToPersist);
    // etc. until you have everything important stored in the bundle
}

Then you use onCreate(Bundle)to get everything out of that persisted bundle and recreate your state.

然后您使用onCreate(Bundle)将所有内容从持久化包中取出并重新创建您的状态。

@Override
onCreate(Bundle savedInstanceState) {
    if(savedInstanceState!=null){ //It could be null if starting the app.
        mCustomObject = savedInstanceState.getSerializable("object_key");
    }
    // etc. until you have reloaded everything you stored
}

Consider the above psuedo-code to point you in the right direction. Reading up on the Activity Lifecycleshould help you determine the best way to accomplish what you're looking for.

考虑上面的伪代码为您指明正确的方向。阅读Activity Lifecycle应该可以帮助您确定完成您正在寻找的工作的最佳方式。

回答by androCoder-BD

simply do this..

简单地做这个..

@Override
public void onBackPressed() {
    //super.onBackPressed();
}

commenting out the //super.onBackPressed(); will do the trick

注释掉 //super.onBackPressed(); 会做的伎俩

回答by Thakur

Try this:

尝试这个:

@Override
public void onBackPressed() {
    finish();
}

回答by Ferran Maylinch

Just in case you want to handle the behaviour of the back button (at the bottom of the phone) and the home button (the one to the left of the action bar), this custom activity I'm using in my project may help you.

以防万一您想处理后退按钮(在手机底部)和主页按钮(操作栏左侧的那个)的行为,我在我的项目中使用的这个自定义活动可能会对您有所帮助.

import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

/**
 * Activity where the home action bar button behaves like back by default
 */
public class BackActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupHomeButton();
    }

    private void setupHomeButton() {
        final ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onMenuHomePressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void onMenuHomePressed() {
        onBackPressed();
    }
}

Example of use in your activity:

在您的活动中的使用示例:

public class SomeActivity extends BackActivity {

    // ....

    @Override
    public void onBackPressed()
    {
        // Example of logic
        if ( yourConditionToOverride ) {
            // ... do your logic ...
        } else {
            super.onBackPressed();
        }
    }    
}

回答by user3156040

@Override
public void onBackPressed() {
// Put your code here.
}

//I had to go back to the dashboard. Hence,

@Override
public void onBackPressed() {
    Intent intent = new Intent(this,Dashboard.class);
    startActivity(intent);
}
Just write this above or below the onCreate Method(within the class)

回答by solaza

In Kotlin:

在科特林:

val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
    // Handle the back button event
}

For more information you can check this.

有关更多信息,您可以查看

There is also specific questionabout overriding back button in Kotlin.

还有一个关于在 Kotlin 中覆盖后退按钮的具体问题