想要获取手机中的应用信息,有两种方式:
MainClass:
packageManager
ResolveInfo
PackageInfo
方法一 packageManager + PackageInfo:
//获取手机中安装的所有应用
fun getPKList(context: Context): List<PackageInfo> {
val pm = context.packageManager
val ip = pm.getInstalledPackages(0) // 获取全部安装的应用
val flag = PackageManager.GET_ACTIVITIES + PackageManager.GET_PERMISSIONS //0 可以是里面的组合,参考源代码
val baiduMap = pm.getInstallerPackageName("com.baidu.BaiduMap")//查询设备是否安装百度地图获取指定应用
ip.iterator().forEach {
if (it.packageName.contains("com.baidu.BaiduMap", true)) { //根据包名过滤应用
Log.e(TAG, "getPackgeList baidu >>${it.packageName}")
val appName = pm.getApplicationLabel(it.applicationInfo) // 更具packageInfo获取应用名称
if (appName.contains("地图")) Log.e(TAG, "appName>>${appName}") // 输出应用名称
}
}
return ip
}
方法二 packageManager + ResolveInfo:
fun getPackageList(context: Context): List<ResolveInfo> {
val pm = context.packageManager
val intent = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_DEFAULT) //获取所安装应用的默认入口Activity
//返回所有应用的入口activty信息
val list = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) //根据过滤条件,过滤Activity
Collections.sort(list, ResolveInfo.DisplayNameComparator(pm)) // 进行排序很重要,排序后才显示第三方app
return list
}
如果想要查询手机中的地图类应用:
//获取手机中的Map应用
fun checkMapAPP(context: Context): List<APPInfo> {
val ip = getPackageList(context)
val pm = context.packageManager
val tempList = ArrayList<APPInfo>()
ip.iterator().forEach {
if (it.activityInfo.packageName.contains(context.resources.getString(R.string.package_name_in_map), true)) {
val appName = it.loadLabel(pm).toString()
if (appName.contains(context.resources.getString(R.string.app_name_in_map))) {
tempList.add(APPInfo(appName, it))
Log.e(TAG, "MAP APP packageName>>${it.activityInfo.packageName}")
Log.e(TAG, "MAP APP resolvePackageName>>${it.resolvePackageName}")
Log.e(TAG, "MAP APP appName>>${appName}")
Log.e(TAG, "MAP APP activityInfo name>>${it.activityInfo.name}")
}
}
}
return tempList
}