0

我需要知道用户何时将我的 android 应用程序发送到后台,然后将其带回前台

当用户将应用程序发送到后台时,我应该执行服务器调用,当回到前台时,我必须清除一些数据

我已经通过以下方式实现了它

public class MyApplication implements Application.ActivityLifecycleCallbacks {

@Override
    public void onActivityStopped(final Activity activity) {

// my logic goes here
}
}

但是这种方式在后台产生了很多 ANR,当我将我的逻辑放在 AsyncTask 中时它不起作用并且它在后台关闭应用程序

谁能建议我如何在不产生 ANR 的情况下以另一种方式满足我的要求

4

3 回答 3

2

最简单的方法是(恕我直言):

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

不要忘记在 build.gradle 中添加:

dependencies {
    implementation "android.arch.lifecycle:extensions:1.1.1"
}
于 2020-04-09T07:58:18.390 回答
0

利用 :

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

当您锁定设备时调用 onStop 和调用 onResume 时,这也可以工作。

于 2017-11-14T10:49:39.123 回答
-1
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;
    }

并在清单中添加以下权限

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
于 2017-11-14T10:51:45.490 回答