衆所周知,通過PackageManager可以擷取手機端已安裝的apk檔案的資訊,具體代碼如下:
PackageManager packageManager =
this.getPackageManager();
List packageInfoList = packageManager.getInstalledPackages(
0);
通過以上方法,可以得到手機中安裝的所有應用程式,既包括了手動安裝的apk包的資訊,也包括了系統預裝的應用軟體的資訊,要區分這兩類軟體可使用以下方法:
a.從packageInfoList擷取的packageInfo,再通過packageInfo.applicationInfo擷取applicationInfo。
b.判斷(applicationInfo.flags& ApplicationInfo.FLAG_SYSTEM)的值,該值大于0時,表示擷取的應用為系統預裝的應用,反之則為手動安裝的應用。
大家可以看下代碼,說明已經寫在注釋中。
擷取應用的代碼:
public
static List getAllApps(Context context) {
List apps =
new ArrayList();
PackageManager pManager = context.getPackageManager();
//
擷取手機内所有應用
List paklist = pManager.getInstalledPackages(
0);
for (
int i =
0; i
PackageInfo pak = (PackageInfo) paklist.
get(i);
//
判斷是否為非系統預裝的應用程式
if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <=
0) {
//
customs applications
apps.add(pak);
}
}
return apps;
}
擷取圖檔、應用名、包名:
PackageManager pManager = MessageSendActivity.
this.getPackageManager();
List appList = Utils.getAllApps(MessageSendActivity.
this);
for(
int i=
0;i
PackageInfo pinfo = appList.
get(i);
ShareItemInfo shareItem =
new ShareItemInfo();
//
set Icon
shareItem.setIcon(pManager.getApplicationIcon(pinfo.applicationInfo));
//
set Application Name
shareItem.setLabel(pManager.getApplicationLabel(pinfo.applicationInfo).toString());
//
set Package Name
shareItem.setPackageName(pinfo.applicationInfo.packageName);
}
其中 ShareItemInfo 類是我本地自定義的,各位可以忽略!
另為,有人可能在找 分享應用清單,在此一并說下吧。
擷取支援分享的應用的代碼:
public
static List getShareApps(Context context){
List mApps =
new ArrayList();
Intent intent=
new Intent(Intent.ACTION_SEND,
null);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setType(
"
text/plain
");
PackageManager pManager = context.getPackageManager();
mApps = pManager.queryIntentActivities(intent,PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
return mApps;
}
由于該方法,傳回的并不是 PackageInfo 對象。而是 ResolveInfo。是以擷取圖檔、應用名、包名的方法不一樣,如下:
PackageManager pManager = MessageSendActivity.
this.getPackageManager();
List resolveList = Utils.getShareApps(MessageSendActivity.
this);
for(
int i=
0;i
ResolveInfo resolve = resolveList.
get(i);
ShareItemInfo shareItem =
new ShareItemInfo();
//
set Icon
shareItem.setIcon(resolve.loadIcon(pManager));
//
set Application Name
shareItem.setLabel(resolve.loadLabel(pManager).toString());
//
set Package Name
shareItem.setPackageName(resolve.activityInfo.packageName);
}
總結:
通過 PackageInfo 擷取具體資訊方法:
包名擷取方法:packageInfo.packageName
icon擷取擷取方法:packageManager.getApplicationIcon(applicationInfo)
應用名稱擷取方法:packageManager.getApplicationLabel(applicationInfo)
使用權限擷取方法:packageManager.getPackageInfo(packageName,PackageManager.GET_PERMISSIONS)
.requestedPermissions
通過 ResolveInfo 擷取具體資訊方法:
包名擷取方法:resolve.activityInfo.packageName
icon擷取擷取方法:resolve.loadIcon(packageManager)
應用名稱擷取方法:resolve.loadLabel(packageManager).toString()