溫馨提示×

android如何獲取正在運行的應(yīng)用

小億
212
2023-09-25 22:42:47
欄目: 編程語言

可以使用ActivityManager類來獲取正在運行的應(yīng)用。以下是一個示例代碼:

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;
}
}

你可以調(diào)用getRunningApps()方法來獲取正在運行的應(yīng)用的名稱列表。

0