package test.example.com.myapplicationui1.Utils;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import java.util.List;
/**
* Created by cgx on 2017/3/24.
*/
public class Utils {
public static boolean isActive;
/*判断应用是否在前台*/
public static boolean isForeground(Context context) {
if (context != null) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> processes = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : processes) {
if (processInfo.processName.equals(context.getPackageName())) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND ||
processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE
) {
return true;
}
}
}
}
return false;
}
}
在基类BaseActivity中重写以下方法
@Override
protected void onResume() {
super.onResume();
if (!Utils.isActive) {
Utils.isActive = true;
onBackToForeground();
}
}
/**
* 从后台切换到前台的操作,例如弹出密码框之类的
*/
protected void onBackToForeground(){
//TODO 可以执行一些公共的业务,子类通过重写该方法进行差异化业务的操作
}
@Override
protected void onStop() {
super.onStop();
if (!Utils.isForeground(this)) {
Utils.isActive = false;
}
}
子类可以通过重写onBackToForeground方法进行差异化操作
@Override
protected void onBackToForeground() {
super.onBackToForeground();
Log.e("back to fore",String.valueOf(Utils.isActive));
}