示例代码
public static void getAppInfo(Context context) {
if (context == null) {
return;
}
ArrayList<String> launchList = getLauncherList(context);
Log.d("getAppInfo", Arrays.toString(new ArrayList[]{launchList}));
List<ApplicationInfo> packageInfos = context.getPackageManager().getInstalledApplications(0);
Log.d("myGetAppInfo", packageInfos.size() + "");
String fileName = "AppInfo.txt";
Uri external = MediaStore.Downloads.EXTERNAL_CONTENT_URI;
ContentResolver resolver = context.getContentResolver();
Uri insertUri;
String selection = MediaStore.Files.FileColumns.DISPLAY_NAME + "='" + fileName + "'";
Cursor cursor = resolver.query(external, null, selection, null, null);
if (cursor != null && cursor.moveToFirst()) {
int columnId = cursor.getColumnIndex(MediaStore.Downloads._ID);
insertUri = Uri.withAppendedPath(external, "" + cursor.getInt(columnId));
} else {
ContentValues values = new ContentValues();
values.put(MediaStore.Files.FileColumns.DISPLAY_NAME, fileName);
values.put(MediaStore.Files.FileColumns.MIME_TYPE, "text/plain");
values.put(MediaStore.Files.FileColumns.TITLE, fileName);
insertUri = resolver.insert(external, values);
}
PrintWriter out = null;
try {
out = new PrintWriter(resolver.openOutputStream(insertUri));
out.println(ServerThread.getDeviceInfo());
for (ApplicationInfo info : packageInfos) {
String packageName = info.packageName;
CharSequence charSequence = context.getPackageManager().getApplicationLabel(info);
String appName = charSequence == null ? "" : charSequence.toString();
String path = info.sourceDir;
String[] pathSplit = path.split("/");
String pathHead = pathSplit[0] + "/" + pathSplit[1] + "/" + pathSplit[2] + "/";
boolean canUninstall = false;
if (pathHead.startsWith("/data/app")) {
canUninstall = true;
}
boolean isLaunchApp = false;
if (launchList.contains(packageName)) {
isLaunchApp = true;
}
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_CONFIGURATIONS);
StringBuilder packageInfoLineBuilder = new StringBuilder();
packageInfoLineBuilder.append(appName).append("@");
packageInfoLineBuilder.append(packageName).append("@");
packageInfoLineBuilder.append(packageInfo.versionName).append("@");
packageInfoLineBuilder.append(isLaunchApp).append("@");
packageInfoLineBuilder.append(canUninstall).append("@");
packageInfoLineBuilder.append(path);
if (isLaunchApp) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
String launchClass = packageName + "/" + intent.getComponent().getClassName();
packageInfoLineBuilder.append("@");
packageInfoLineBuilder.append(launchClass);
}
out.println(packageInfoLineBuilder.toString());
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
Android11以及以上版本需要在AndroidManifest.xml中添加以下权限,否则有很多APP获取不到:
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>