安卓判断APP是在前台还是在后台
安卓中判断APP是否在前台:
方法一:CCApplication 中判断
private boolean mIsInForeground = false;
public boolean isInForeground() {
return mIsInForeground;
}
private class CCActivityLifecycleCallbacks implements ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
MonkeyLog.d(TAG, "onActivityStarted :" + activity);
}
@Override
public void onActivityResumed(Activity activity) {
mIsInForeground = true;//APP在前端
Adjust.onResume();
setCurrentActivity(activity);
}
@Override
public void onActivityPaused(Activity activity) {
mIsInForeground = false;//APP 在后台
Adjust.onPause();
setCurrentActivity(null);
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
在APPlication的onCreate()方法中:
registerActivityLifecycleCallbacks(new CCActivityLifecycleCallbacks());
使用的时候直接判断:
if (!CCApplication.getInstance().isInForeground()) {
//ToDo
}
方法二:
在BaseActivity中
// 当前app是否是前台状态
private static boolean isActive = false;
在BaseActivity 的onResume()方法中:
@Override
protected void onResume() {
super.onResume();
if (!isActive) {
//app 从后台唤醒,进入前台
isActive = true;
}
}
在onStop()方法中:
@Override
protected void onStop() {
super.onStop();
if (!isAppOnForeground()) {
//app 进入后台
isActive = false;
}
}
/**
* 程序是否在前台运行
*
* @return
*/
private 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<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;
}
这样就可以判断APP是在前台还是在后台了
常用的地方是当接收到Notification消息时,当APP在前端直接处理消息 当APP在后台时 将Notification消息显示在手机的消息栏中
个人GitHub地址:https://github.com/HuaDanJson
还没有评论,来说两句吧...