1. 判断APP是否在前台运行
public static boolean isRunningForeground(Context context) {
ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcessInfos = activityManager.getRunningAppProcesses();
// 枚举进程
for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfos) {
if (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
if (appProcessInfo.processName.equals(context.getApplicationInfo().processName)) {
return true;
}
}
}
return false;
}
2. 将APP切换到前台
//如果APP是在后台运行
if (!AllUtils.isRunningForeground(this)) {
//获取ActivityManager
ActivityManager mAm = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//获得当前运行的task
List<ActivityManager.RunningTaskInfo> taskList = mAm.getRunningTasks(100);
for (ActivityManager.RunningTaskInfo rti : taskList) {
//找到当前应用的task,并启动task的栈顶activity,达到程序切换到前台
if (rti.topActivity.getPackageName().equals(getPackageName())) {
mAm.moveTaskToFront(rti.id, 0);
return;
}
}
//若没有找到运行的task,用户结束了task或被系统释放,则重新启动mainactivity
Intent resultIntent = new Intent(MainActivity.this, MainActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(resultIntent);
}
3. 必须添加的权限
<!--前后台的切换-->
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL"/>
<uses-permission android:name="android.permission.GET_TOP_ACTIVITY_INFO"/>
<uses-permission android:name="android.permission.REORDER_TASKS"/>
4.
5.
6.
7.
8.