温馨提示×

android如何获取正在运行的应用

小亿
222
2023-09-25 22:42:47
栏目: 编程语言

可以使用ActivityManager类来获取正在运行的应用。以下是一个示例代码:

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class RunningAppUtils {
public static List<String> getRunningApps(Context context) {
List<String> runningApps = new ArrayList<>();
PackageManager packageManager = context.getPackageManager();
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningAppProcesses) {
try {
ApplicationInfo appInfo = packageManager.getApplicationInfo(processInfo.processName, PackageManager.GET_META_DATA);
String appName = (String) packageManager.getApplicationLabel(appInfo);
runningApps.add(appName);
} catch (PackageManager.NameNotFoundException e) {
Log.e("RunningAppUtils", "Failed to get app name for process: " + processInfo.processName);
}
}
return runningApps;
}
}

你可以调用getRunningApps()方法来获取正在运行的应用的名称列表。

0