简体   繁体   English

如何知道您何时因为返回按钮而返回活动?

[英]How to know when you returned to an activity because of the back button?

My MainActivity leads to SecondActivity.我的 MainActivity 导致 SecondActivity。 If the user presses the phone's back button the app goes back to the MainActivity.如果用户按下手机的后退按钮,应用程序将返回 MainActivity。

How can I execute something when this happens?发生这种情况时我该如何执行?

(I know I could put code in SecondActivity to add functionality to the back button so it passes a result to MainActivity, but I don't want to do that to every possible screen that could lead back to the MainActivity.) (我知道我可以在 SecondActivity 中添加代码以向后退按钮添加功能,以便将结果传递给 MainActivity,但我不想对可能导致返回 MainActivity 的每个可能的屏幕都这样做。)

Perhaps another way of asking, how can I know that MainActivity is showing because of pressing the back button rather than having been formally requested with an intent?也许换一种方式问,我怎么知道 MainActivity 是因为按下后退按钮而不是被正式请求而显示的?

Background背景

I think here is the logic to implement this requirement:我认为这是实现此要求的逻辑:

  1. When users press the back key on the current activity, we will remember that action.当用户在当前活动上按下返回键时,我们会记住那个动作。

  2. When users go back to the previous activity, we will check whether there is a back key pressed action exits or not.当用户 go 回到上一个活动时,我们将检查是否有返回键按下动作退出。

Implementation执行

Step 1. Create a base activity class named BaseActivity .步骤 1.创建一个名为 BaseActivity 的基础活动BaseActivity Every activity in your app should extend from this class.您应用程序中的每个活动都应该从这个 class 扩展。

class BaseActivity extends AppCompatActivity {

    public static String IS_BACK_KEY_PRESSED = "IS_BACK_KEY_PRESSED";

    @Override
    public void onBackPressed() {
        // Remember the user's press of the back key action
        getIntent().putExtra(IS_BACK_KEY_PRESSED, true);

        // Call the super's method
        super.onBackPressed();
    }

    /**
     * Called when the activity has been resumed from an activity
     * that has been destroyed because of user's press of the back key
     */
    public void onGoBackFromAnotherActivity() {
    }
}

Step 2. Create a class named MyApp that extends from the Application class.步骤 2.创建一个名为MyApp的 class,它从应用程序 class 扩展而来。 Its purpose is to listen to all activity lifecycle of the app by using registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks)其目的是通过使用registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks)监听应用程序的所有活动生命周期

public class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacksImpl());
    }

    private static final class ActivityLifecycleCallbacksImpl implements ActivityLifecycleCallbacks {
        boolean isBackKeyPressed = false;

        @Override
        public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        }

        @Override
        public void onActivityStarted(@NonNull Activity activity) {
            if (activity instanceof BaseActivity) {
                if (isBackKeyPressed) {
                    ((BaseActivity) activity).onGoBackFromAnotherActivity();
                    isBackKeyPressed = false;
                }
            }
        }

        @Override
        public void onActivityResumed(@NonNull Activity activity) {
        }

        @Override
        public void onActivityPaused(@NonNull Activity activity) {
            if (activity instanceof BaseActivity) {
                Bundle data = activity.getIntent().getExtras();
                if (data != null) {
                    isBackKeyPressed = data.getBoolean(BaseActivity.IS_BACK_KEY_PRESSED);
                } else {
                    isBackKeyPressed = false;
                }
            }
        }

        @Override
        public void onActivityStopped(@NonNull Activity activity) {
        }

        @Override
        public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
        }

        @Override
        public void onActivityDestroyed(@NonNull Activity activity) {
        }
    }
}

Remember to add this class to AndroidManifest.xml记得把这个 class 添加到AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.kotlinapp">

    <application
        android:name=".MyApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity" />

    </application>

</manifest>

Usage用法

MainActivity.java MainActivity.java

public class MainActivity extends BaseActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onGoBackFromAnotherActivity() {
        // Your code logic goes here.
    }
}

SecondActivity.java SecondActivity.java

public class SecondActivity extends BaseActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }
}

Edit: Check if any activity (without knowing which) returned to desired activity编辑:检查是否有任何活动(不知道是哪个活动)返回到所需的活动

To check in Activity A, use:要签入活动 A,请使用:

@Override
protected void onResume() {
    super.onResume();
    // TODO: Work
}

As stated in the comment, onResume will be called on an activity/fragment when:如评论中所述, onResume将在以下情况下在活动/片段上调用:

  1. Activity runs for the first time活动首次运行
  2. Activity comes back into focus (from another activity, launcher, recent, another app)活动重新成为焦点(来自另一个活动、启动器、最近的、另一个应用程序)

However, you cannot track what triggered it, or what happened before it.但是,您无法跟踪是什么触发了它,或者它之前发生了什么。


---------- Outdated ---------- ---------- 过时 ----------


Between Activity A and Activity B活动 A 和活动 B 之间

use利用

startActivityForResult(intent, CHOOSE_AN_INT_VALUE_TO_INDICATE_IT_REQUESTS_FOR_BACK_PRESS);

In Activity A, and in Activity B, use在活动 A 和活动 B 中,使用

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

Then again in Activity A, use然后再次在活动 A 中,使用

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CHOOSE_AN_INT_VALUE_TO_INDICATE_IT_REQUESTS_FOR_BACK_PRESS && resultCode==CHOOSE_AN_INT_VALUE_TO_INDICATE_IT_CAME_FROM_BACK_PRESS) {
        // TODO: Do your work
    }
}

If these 3 portions are implemented, you don't need to check for which activity triggered back press, you can simply compare the request and result codes如果这3部分都实现了,就不需要检查是哪个activity触发了back press,你可以简单的对比一下request和result code

I hope this helps!!我希望这有帮助!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在按下“返回”按钮之前保存字符串,并在返回活动时将其取回? - How to save a string before a Back button press, and retrieve it when you go back to the activity? 如何创建可以覆盖主屏幕但在按下主页或后退按钮时不会关闭的透明活动? - How do you create a transparent activity that can overlay the home screen but is not dismissed when the home or back button is pressed? 按下“后退”按钮时如何返回上一个活动? - How to go back to Previous Activity when Back button is pressed? 如何知道何时从片段返回到活动 - How to know when you return from a Fragment to an Activity 按下后退按钮时如何删除堆栈中的所有活动 - How to remove all activity in Stack when press back button Android - 如何在按下默认后退按钮时为活动转换设置动画 - Android - How to animate an activity transition when the default back button is pressed 按下后退按钮时如何从“滑动”面板导航到“活动” - How to navigate to Activity from Sliding panel when the back button is pressed Android“后退”按钮停止导航到父活动,因为用户未登录 - Android "back" button stop navigating to parent activity, because user is not logged in 如何在按下“后退”按钮时阻止活动重新开始? - How to stop an activity from restarting when back button is pressed? 按下“后退”按钮时如何终止活动? - How do I kill an Activity when the Back button is pressed?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM