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

时间:2018-02-14 12:08:19

标签: android background

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

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

1 个答案:

答案 0 :(得分: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
    }

}