Android的ActivityManager類是一個系統(tǒng)級服務(wù),用于管理應(yīng)用程序的Activity,如啟動Activity、關(guān)閉Activity、獲取運行中的Activity等。下面是一些常用的ActivityManager的使用方法:
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTasks = activityManager.getRunningTasks(10);
for (ActivityManager.RunningTaskInfo taskInfo : runningTasks) {
ComponentName componentName = taskInfo.topActivity;
Log.d(TAG, "topActivity: " + componentName.getPackageName() + "/" + componentName.getClassName());
}
Intent intent = new Intent(context, YourActivity.class);
startActivity(intent);
finish();
或者
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
activityManager.finishActivity(ActivityId);
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
activityManager.restartPackage(getPackageName());
List<ActivityManager.RunningTaskInfo> runningTasks = activityManager.getRunningTasks(1);
if (!runningTasks.isEmpty()) {
ComponentName topActivity = runningTasks.get(0).topActivity;
if (topActivity.getPackageName().equals(getPackageName())) {
// 當(dāng)前應(yīng)用在前臺運行
}
}
需要注意的是,由于Android系統(tǒng)的各個版本可能存在差異,因此在使用ActivityManager時,需要根據(jù)具體的情況做相應(yīng)的兼容處理。