1.通過(guò)文件下載的路徑得到程序包名
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);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? //判斷包名是否在系統(tǒng)包名列表中
? ? ? ? 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);
? ? }