简体   繁体   English

更改应用时调用的活动onResume()

[英]Activity onResume( ) called when changing apps

I would like to know if there's a way to differentiate when the onResume() method of an activity is called from the same app or a different application. 我想知道是否有办法区分何时从同一个应用程序或不同的应用程序调用活动的onResume()方法。

For example I would like to differentiate when my main activity's onResume() is called when I return to the app from Whatsapp or another activity of my app. 例如,当我从Whatsapp或我的应用程序的其他活动返回应用程序时,我想区分何时调用我的主要活动的onResume()。

I know there's a way to do it with GET_TASKS permission but that method is deprecated and not recommended. 我知道有一种方法可以使用GET_TASKS权限,但该方法已弃用,不推荐使用。

Thank you 谢谢

It appears you want to know when app comes from the background to foreground in each Activity . 您似乎想知道应用程序何时从每个Activity前景到前景。 This can be achieved using a class that extends the Application class and implements the ActivityLifecycleCallbacks interface. 这可以使用扩展Application类并实现ActivityLifecycleCallbacks接口的类来实现。 Firstly, here's the code for this class: 首先,这是这个类的代码:

public class MyApplication extends Application implements ActivityLifecycleCallbacks {

    public boolean appInBackground;
    private Handler mHandler;  

    ...  

    @Override   
    public void onActivityResumed(Activity activity) {
        Log.i("Activity Resumed", activity.getLocalClassName());

        mHandler.cancelCallbacksAndMessages(null);  
        appInBackground = false;
    }   

    @Override   
    public void onActivityPaused(Activity activity) {
        Log.i("Activity Paused", activity.getLocalClassName());

        mHandler.postDelayed(new Runnable() {
             @Override  
             public void run() {  
                  appInBackground = true;
             }  
        }, 5000);  
    }   

    ...  

} 

If you notice in above code we are basically giving the app a grace period of 5 seconds to switch from one activity to other. 如果您在上面的代码中注意到我们基本上给应用程序一个5秒的宽限期来从一个活动切换到另一个活动。 If it exceeds more than that, it means the app was in background. 如果超过该值,则表示应用程序处于后台。 The above class will need to registered in the <application> tag of your manifest file under android:name:"" property as android:name:"MyApplication" . 上面的类需要在你的清单文件的<application>标签中注册android:name:""属性为android:name:"MyApplication"

To use this in your activity, override the onPause() : 要在您的活动中使用它,请覆盖onPause()

private boolean resumedFromBg;

@Override
protected void onPause() {
    super.onPause();
    resumedFromBg = ((MyApplication) getApplication()).appInBackground;
}

Let me know if you run into any issues~ 如果您遇到任何问题,请告诉我〜

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM