转载于:https://blog.csdn.net/gouguofei/article/details/7775752
基本思路:
就是让app中所有的activity继承与一个公共的activity(例如:BaseActivity),然后在BaseActivity的onStop()中判断当前程序是否处于后台
- public class BaseActivity extends Activity {
- @Override
- protected void onStop() {
- // TODO Auto-generated method stub
- super.onStop();
- if (!isAppOnForeground()) {
- //app 进入后台
- //全局变量isActive = false 记录当前已经进入后台
- }
- }
- @Override
- protected void onResume() {
- // TODO Auto-generated method stub
- super.onResume();
- //if (!isActive) {
- //app 从后台唤醒,进入前台
- //isActive = true;
- //}
- }
- /**
- * 程序是否在前台运行
- *
- * @return
- */
- public boolean isAppOnForeground() {
- // Returns a list of application processes that are running on the
- // device
- ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
- String packageName = getApplicationContext().getPackageName();
- List<RunningAppProcessInfo> appProcesses = activityManager
- .getRunningAppProcesses();
- if (appProcesses == null)
- return false;
- for (RunningAppProcessInfo appProcess : appProcesses) {
- // The name of the process that this object is associated with.
- if (appProcess.processName.equals(packageName)
- && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
- return true;
- }
- }
- return false;
- }
- }