如何监听android程序进入后台,和恢复到前台

2024-12-04 04:30:45
推荐回答(1个)
回答1:

就是让app中所有的activity继承与一个公共的activity(例如:BaseActivity),然后在BaseActivity的onStop()中判断当前程序是否处于后台
/**
* 文件名:BaseActivity.java
* 版本号:

* 变更:
*/

package com.wadata.mobilefollowup.view.base;

import java.util.List;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;

/**
* 名称:BaseActivity
* 描述:
* 创建人:

* 变更:
*/

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