Android - 如何覆盖“返回”按钮,这样它就不会 Finish() 我的 Activity?

发布于 2024-09-07 07:41:52 字数 1172 浏览 11 评论 0原文

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

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

当用户按下后退按钮时,问题就出现了,我的 Activity 被销毁,但通知仍然存在,因为我希望用户能够按后退按钮,但仍然能够通过通知访问 Activity。但是,当用户尝试此操作时,我会得到空指针,因为它试图开始一项新活动,而不是恢复旧活动。

所以本质上我希望“后退”按钮的行为与“主页”按钮完全相同,这是我到目前为止的尝试:


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

但是上面的代码似乎仍然允许我的 Activity 被销毁,如何阻止我的 Activity 在以下情况下被销毁:后退按钮被按下?

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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

小矜持 2024-09-14 07:41:52

删除您的按键侦听器或在有 KEY_BACK 时返回 true

您只需要以下代码即可捕获后退键(确保不要在 onBackPressed() 中调用 super)。

另外,如果您计划在后台运行某个服务,请务必查看 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);
}

Remove your key listener or return true when you have KEY_BACK.

You just need the following to catch the back key (Make sure not to call super in 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.

@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);
}
那请放手 2024-09-14 07:41:52

只需一行代码就可以更轻松地实现它:

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

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

@Override
public void onBackPressed() {
   moveTaskToBack(true);
}
下雨或天晴 2024-09-14 07:41:52

只需这样做..

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

注释掉 //super.onBackPressed();会成功的

simply do this..

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

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

牵你的手,一向走下去 2024-09-14 07:41:52

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

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

然后你使用 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
}

考虑上面的伪代码来为您指明正确的方向。阅读活动生命周期应该可以帮助您确定完成任务的最佳方式你在寻找什么。

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 Lifecycle and persist your settings/data in the onSaveInstanceState(Bundle) event.

@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.

@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 Lifecycle should help you determine the best way to accomplish what you're looking for.

我们的影子 2024-09-14 07:41:52

试试这个:

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

Try this:

@Override
public void onBackPressed() {
    finish();
}
月下伊人醉 2024-09-14 07:41:52

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

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

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

public class SomeActivity extends BackActivity {

    // ....

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

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();
        }
    }    
}
海未深 2024-09-14 07:41:52
@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)
@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)
芯好空 2024-09-14 07:41:52

在 Kotlin 中:

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

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

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

In Kotlin:

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

For more information you can check this.

There is also specific question about overriding back button in Kotlin.

海螺姑娘 2024-09-14 07:41:52

看起来我已经很晚了,但对于那些需要切换到新屏幕并清除后退按钮堆栈的人来说,这里是一个非常简单的解决方案。

startActivity(new Intent(this,your-new-screen.class));
finishAffinity();

完成亲和力();方法清除后退按钮堆栈。

Looks like im very late but for those of you who need to switch to new screen and clear back button stack here is a very simple solution.

startActivity(new Intent(this,your-new-screen.class));
finishAffinity();

The finishAffinity(); method clears back button stack.

此生挚爱伱 2024-09-14 07:41:52

就这样做

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

just do this

@Override
public void onBackPressed() {
    super.onBackPressed();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文