1. 程式人生 > >Android 從後臺進入前臺

Android 從後臺進入前臺

public void moveTaskToFront(int taskId, int flags) {

try {
ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags);
} catch (RemoteException e) {
// System dead, we will be dead too soon!

}

//獲取ActivityManager

ActivityManager mAm = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);

//獲得當前執行的task

List<ActivityManager.RunningTaskInfo> taskList = mAm.getRunningTasks(100);

for(ActivityManager.RunningTaskInfo rti : taskList) {

//找到當前應用的task,並啟動task的棧頂activity,達到程式切換到前臺

if(rti.topActivity.getPackageName().equals(context.getPackageName())) {

mAm.moveTaskToFront(rti.id,0);

return;

}

}

//若沒有找到執行的task,使用者結束了task或被系統釋放,則重新啟動mainactivity

Intent resultIntent = newIntent(context, MainActivity.class);

resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);

context.startActivity(resultIntent);