可以使用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()
方法來獲取正在運行的應用的名稱列表。