1.通过文件下载的路径得到程序包名
public static String getPackage(Context context, String filePath) {
String packageName = "";
PackageManager pm = context.getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(filePath,
PackageManager.GET_ACTIVITIES);
if (info != null) {
packageName = info.packageName;
int versionCode = info.versionCode;
}
return packageName;
}
2.打开apk
public static void openApk(Context context, String packageName) {
Intent LaunchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
context.startActivity(LaunchIntent);
}
public static Boolean isInstall(Context context, String packageName) {
final PackageManager packageManager = context.getPackageManager();
//取得所有的PackageInfo
List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
List<String> pName = new ArrayList<>();
if (pinfo != null) {
for (int i = 0; i < pinfo.size(); i++) {
String pn = pinfo.get(i).packageName;
pName.add(pn);
}
}
//判断包名是否在系统包名列表中
return pName.contains(packageName);
}
3.安装程序
public static void installApk(Context context,String filePath) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
File file=new File(filePath);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0+以上版本
Uri apkUri = FileProvider.getUriForFile(context, "cn.wlantv.kznk.fileprovider", file); //与manifest中定义的provider中的authorities="cn.wlantv.kznk.fileprovider"保持一致
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
context.startActivity(intent);
}
网友评论