Android监听程序进入后台,或者恢复到前台

判断当前app是否从后台运行还是在前台运行或者从后台转到前台:
就是让app中所有的activity继承与一个公共的activity(例如:BaseActivity),然后在BaseActivity的onStop()中判断当前程序是否处于后台

核心代码

public class BaseActivity extends AppCompatActivity {

    private final String TAG = getClass().getSimpleName();

    @Override
    protected void onStop() {

        super.onStop();

        if (!isAppOnForeground()) {
            //app 进入后台
            Log.i(TAG, "从前台返回到后台");
            //全局变量isActive = false 记录当前已经进入后台
            ComConstant.setIsActive(false);
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Log.i(TAG, "BaseActivity - onResume");
        if (!ComConstant.isActive()) {
            Log.i(TAG, "从后台返回到前台");
            ComConstant.setIsActive(true);
        }
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public boolean isAppOnForeground() {

        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();

        List appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }
}

你可能感兴趣的:(Android基础)