android 获取包名的两种方式
用到的类PackageManager
java.lang.Object
↳ android.content.pm.PackageManager
PackageManager packageManager = getPackageManager();
int flag = PackageManager.GET_UNINSTALLED_PACKAGES;
/*
GET_UNINSTALLED_PACKAGES 这个常数在API级别24中被弃用。用MATCH_UNINSTALLED_PACKAGES替换
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
flag = PackageManager.MATCH_UNINSTALLED_PACKAGES;
}
//方法一
List<PackageInfo> installedPackages = packageManager.getInstalledPackages(flag);
for (PackageInfo installedPackage : installedPackages) {
Log.i(TAG, "----------packagename = " + installedPackage.packageName);
}
//方法一
List<ApplicationInfo> listAppcations = packageManager.getInstalledApplications(flag);
Collections.sort(listAppcations, new ApplicationInfo.DisplayNameComparator(packageManager));
for (ApplicationInfo info : listAppcations) {
Log.i(TAG, "----------packagename = " + info.packageName);
}