简体   繁体   English

如何检测 android 应用程序何时在后台和前台处理一些代码

[英]how to detect when android app in background and foreground to handle some code

I need to know when user send my android app to background and then bring it back to foreground我需要知道用户何时将我的 android 应用程序发送到后台,然后将其带回前台

when user send app to background I should perform server call and when back to foreground I have to clear some data当用户将应用程序发送到后台时,我应该执行服务器调用,当回到前台时,我必须清除一些数据

I have implemented it in the following way我已经通过以下方式实现了它

public class MyApplication implements Application.ActivityLifecycleCallbacks {

@Override
    public void onActivityStopped(final Activity activity) {

// my logic goes here
}
}

but this way make a lot of ANRs in background, and when I put my logic inside AsyncTask it does not work and also it close app in background但是这种方式会在后台产生很多 ANR,当我将我的逻辑放入 AsyncTask 时它不起作用并且它还会在后台关闭应用程序

can any one advice me how to meet my requirement in another way without generating ANR's谁能建议我如何以另一种方式满足我的要求而不产生 ANR

The easiest way to do it is (IMHO):最简单的方法是(恕我直言):

public class YourApplication extends Application implements LifecycleObserver {

    @Override
    public void onCreate() {
        super.onCreate();
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private void onAppBackgrounded() {
        Log.d("YourApplication", "YourApplication is in background");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private void onAppForegrounded() {
        Log.d("YourApplication", "YourApplication is in foreground");
    }
}

Do not forget to add in build.gradle:不要忘记在 build.gradle 中添加:

dependencies {
    implementation "android.arch.lifecycle:extensions:1.1.1"
}

Use :采用 :

@Override
    public void onStop()
    {
        super.onStop();
        // Do your stuff here when you are stopping your activity
    }

@Override
    public void onResume()
    {
        super.onResume();
        // Do your stuff here when comes back to activity
    }

This can also work when you lock your device onStop is called and when you reopen onResume is called.这也可以在您锁定设备时调用 onStop 并且重新打开时调用 onResume 时起作用。

In your Application class, you can add this code:在您的申请 class 中,您可以添加以下代码:

ProcessLifecycleOwner.get().getLifecycle().addObserver(new DefaultLifecycleObserver() {
        @Override
        public void onStop(@NonNull LifecycleOwner owner) { /* code here */ }});

More about it, here https://developer.android.com/reference/androidx/lifecycle/ProcessLifecycleOwner更多信息,在这里https://developer.android.com/reference/androidx/lifecycle/ProcessLifecycleOwner

private boolean isAppInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }

and add below permission in manifest并在清单中添加以下权限

<uses-permission android:name="android.permission.GET_ACCOUNTS" />

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

相关问题 如何检测Android应用程序何时进入后台并返回前台 - How to detect when an Android app goes to the background and come back to the foreground Android-检测应用移至背景和前景 - Android - Detect app moving to background and foreground 当应用程序处于前台或后台时如何使用 FCM 处理通知 - How to handle notifications with FCM when app is in either foreground or background 如何检测任何应用程序何时进入前台或在 android 中启动? - How to detect when any app comes to foreground or lauched in android? 当应用程序在 android 中从后台转到前台时如何重新启动应用程序? - How to relaunch application when app went to background to foreground in android? Android-在前台运行应用程序时处理本地通知 - Android - Handle local notification when app in foreground 如何检测Android中何时有应用程序出现 - How to detect whenever app comes to foreground in android 运行前台服务时如何检测当前的前台应用程序 - How to detect current foreground app when foreground service is running 应用程序在前台时如何处理Firebase通知 - How to handle the Firebase notification when app is in foreground 如何将Android应用程序从前台传递到后台 - How to pass Android app from foreground to background
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM