Android PackageManager 使用简单记录

Android 为我们提供了一个能够获取Package的信息的类PackageManager,从中我们可以通过包名获取到例如App名称,桌面图标等应用信息。简单记录一下如何使用PackageManager获取对应的信息吧。

获取App Name

1
2
3
4
5
6
7
8
9
10
public String getApplicationNameByPackageName(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
String Name;
try {
Name = pm.getApplicationLabel(pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA)).toString();
} catch (PackageManager.NameNotFoundException e) {
Name = "";
}
return Name;
}

获取桌面图标

1
2
3
4
5
6
7
8
9
10
public Drawable getAppIconByPacakgeName(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
Drawable icon;
try {
icon = pm.getApplicationIcon(packageName);
} catch (PackageManager.NameNotFoundException e) {
icon = ContextCompat.getDrawable(context, R.mipmap.ic_launcher);
}
return icon;
}