当我的应用程序转到后台时清除数据

问题描述 投票:0回答:1

我希望在用户直接关闭应用程序时清除一些会话数据意味着如果应用程序转到后台我想清除数据,我如何识别应用程序转到后台,我尝试了很多解决方案,但它们对我不起作用,

 private boolean isAppIsInBackground(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;
}

我正在使用这种方法来查找状态,我也尝试了另一个也不适合我的过程。

我使用Application.ActivityLifecycleCallbacks这个过程也是我无法找到的,我在Application类中调用了这个。

public class MyApplicationClass extends Application {


private static final String TAG = MyApplicationClass.class.getSimpleName();

private static MyApplicationClass sInstance;

@Nullable
public static Context getAppContext() {
    return sInstance;
}

@Override
public void onCreate() {
    super.onCreate();
    Toast.makeText(this,"onCreate",Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate() called");
    sInstance = this;
    registerActivityLifecycleCallbacks(new ActivityCallbackApplication());
}
android background
1个回答
0
投票

查看Google https://developer.android.com/topic/libraries/architecture/lifecycle.html的新生命周期组件

它可以让您轻松控制生命周期

public class MyApplicationClass extends Application implements LifecycleObserver {

    private static final String TAG = MyApplicationClass.class.getSimpleName();

    private static MyApplicationClass sInstance;

    @Nullable
    public static Context getAppContext() {
        return sInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this,"onCreate",Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate() called");
        sInstance = this;
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onBecameBackground() {
        // clear data here
    }

}

© www.soinside.com 2019 - 2024. All rights reserved.