android 如何监听程序从前台转入后台
1个回答
展开全部
一、通过ActivityManager.RunningAppProcessInfo判断
首先,我们需要写一个BaseActivity,然后让我们应用程序的Activity都继承自BaseActivity,这样就可以统一管理,然后在BaseActivity的onResume()和onStop()方法中进行判断应用程序是否进入到后台并且是否从后台返回到了前台,直接看代码:
public class BaseActivity extends Activity {
public static boolean isActive; //全局变量
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
}
@Override
protected void onResume() {
if (!isActive) {
//app 从后台唤醒,进入前台
isActive = true;
Log.i("ACTIVITY", "程序从后台唤醒");
}
super.onResume();
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
if (!isAppOnForeground()) {
//app 进入后台
isActive = false;//记录当前已经进入后台
Log.i("ACTIVITY", "程序进入后台");
}
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/**
* APP是否处于前台唤醒状态
*
* @return
*/
public boolean isAppOnForeground() {
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
String packageName = getApplicationContext().getPackageName();
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
if (appProcesses == null)
return false;
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
// The name of the process that this object is associated with.
if (appProcess.processName.equals(packageName)
&& appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
return false;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询