Android 中获取Apk的包名和类名的实现方法
在安卓开发的过程中有时候我们需要调用第三方APK应用的时候,并不知道其中的包名和类名,可以调用下面的方法获取所需要的包名和类名。
/**
*
* 通过APK地址获取此APP的包名和版本等信息
* */
private void getPackageName() {
String FilePath="*.apk";//输入APK地址
PackageManager pm = getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(FilePath, PackageManager.GET_ACTIVITIES);
if(info != null){
ApplicationInfo appInfo = info.applicationInfo;
String appName = pm.getApplicationLabel(appInfo).toString();
String packageName = appInfo.packageName; //获取安装包名称
Log.i("Abel_Test", "包名是:"+packageName);
String version=info.versionName; //获取版本信息
Log.i("Abel_Tes", "版本信息:"+version);
}
}
/**
*
* 通过包名获取此APP详细信息,包括Activities、services、versioncode、name等等 并且可以直接调用
* */
private void doStartApplicationWithPackageName(String packagename) {
PackageInfo packageinfo = null;
try {
packageinfo = getPackageManager().getPackageInfo(packagename, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
if (packageinfo == null) {
return;
}
// 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resolveIntent.setPackage(packageinfo.packageName);
// 通过getPackageManager()的queryIntentActivities方法遍历
List<ResolveInfo> resolveinfoList = getPackageManager()
.queryIntentActivities(resolveIntent, 0);
ResolveInfo resolveinfo = resolveinfoList.iterator().next();
if (resolveinfo != null) {
// packagename = 参数packname
String packageName = resolveinfo.activityInfo.packageName;
// 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式:packagename.mainActivityname]
String className = resolveinfo.activityInfo.name;
Log.i("Abel_Test", "类名是:"+className);
// LAUNCHER Intent
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
// 设置ComponentName参数1:packagename参数2:MainActivity路径
ComponentName cn = new ComponentName(packageName, className);
intent.setComponent(cn);
startActivity(intent);
}
}