Android的ActivityManager類是一個系統級服務,用于管理應用程序的Activity,如啟動Activity、關閉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())) {
// 當前應用在前臺運行
}
}
需要注意的是,由于Android系統的各個版本可能存在差異,因此在使用ActivityManager時,需要根據具體的情況做相應的兼容處理。