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时,需要根据具体的情况做相应的兼容处理。