- 判斷APP是否在前臺(tái)運(yùn)行
- 將APP切換到前臺(tái)
-
-
-
-
-
-
1. 判斷APP是否在前臺(tái)運(yùn)行
public static boolean isRunningForeground(Context context) {
ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcessInfos = activityManager.getRunningAppProcesses();
// 枚舉進(jìn)程
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切換到前臺(tái)
//如果APP是在后臺(tái)運(yùn)行
if (!AllUtils.isRunningForeground(this)) {
//獲取ActivityManager
ActivityManager mAm = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//獲得當(dāng)前運(yùn)行的task
List<ActivityManager.RunningTaskInfo> taskList = mAm.getRunningTasks(100);
for (ActivityManager.RunningTaskInfo rti : taskList) {
//找到當(dāng)前應(yīng)用的task蝗茁,并啟動(dòng)task的棧頂activity朽寞,達(dá)到程序切換到前臺(tái)
if (rti.topActivity.getPackageName().equals(getPackageName())) {
mAm.moveTaskToFront(rti.id, 0);
return;
}
}
//若沒(méi)有找到運(yùn)行的task悼尾,用戶結(jié)束了task或被系統(tǒng)釋放乳蛾,則重新啟動(dòng)mainactivity
Intent resultIntent = new Intent(MainActivity.this, MainActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(resultIntent);
}
3. 必須添加的權(quán)限
<!--前后臺(tái)的切換-->
<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.
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者