Android 前后台运行切换监听

1.app从前台进入后台运行

写一MyApplication集成Application,重写onTrimMemory方法,判断level值是否等于TRIM_MEMORY_UI_HIDDEN,相等即表示app切换到了后台。

 @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if (level == TRIM_MEMORY_UI_HIDDEN){
            Toast.makeText(this, "app进入后台运行", Toast.LENGTH_SHORT).show();
        }
    }

2.app从后台进入前台

同样在Application中监听,重写onCreate()方法,实现registerActivityLifecycleCallbacks接口,然后在onActivityResumed表示进入到了前台运行。

@Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {
                Toast.makeText(mContext, "app进入前台", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

你可能感兴趣的:(Android 前后台运行切换监听)