應用內更新安裝
阿新 • • 發佈:2018-12-18
各個版本應用安裝方法
- 1、各個版本判斷
// filepath 檔案路徑
private static void installAPK(Context context, String filePath) {
if (Build.VERSION.SDK_INT < 23) {
Intent intents = new Intent();
intents.setAction(Intent.ACTION_VIEW);
// intents.addCategory("android.intent.category.DEFAULT");
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intents.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
context.startActivity(intents);
} else if (Build.VERSION.SDK_INT >= 24) {
install(context, filePath);
} else {
File file = new File(filePath);
if (file.exists()) {
openFile(file, context);
} else {
}
}
}
- 2、安裝
/** * android7.0之後的更新 * 通過隱式意圖呼叫系統安裝程式安裝APK */ private static void install(Context context, String filePath) { File file = new File(filePath); Intent intent = new Intent(Intent.ACTION_VIEW); // 引數1 上下文, 引數2 Provider主機地址 和配置檔案中保持一致 引數3 共享的檔案 String packageName = 獲取你自己應用的包名; Uri apkUri = FileProvider.getUriForFile(context, packageName, file); intent.addCategory("android.intent.category.DEFAULT"); // 由於沒有在Activity環境下啟動Activity,設定下面的標籤 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 新增這一句表示對目標應用臨時授權該Uri所代表的檔案 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(apkUri, "application/vnd.android.package-archive"); context.startActivity(intent); } /** * android6.0之後的升級更新 * * @param file * @param context */ @SuppressLint("WrongConstant") private static void openFile(File file, Context context) { Intent intent = new Intent(); intent.addFlags(268435456); intent.setAction("android.intent.action.VIEW"); String type = getMIMEType(file); intent.setDataAndType(Uri.fromFile(file), type); try { context.startActivity(intent); } catch (Exception var5) { var5.printStackTrace(); Toast.makeText(context, context.getResources().getString(R.string.no_install_program), Toast.LENGTH_SHORT).show(); } } private static String getMIMEType(File var0) { String var1 = ""; String var2 = var0.getName(); String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase(); var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3); return var1; }
注意點
android 8.0安裝需要許可權
同時需要新增provider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="你自己的app包名"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
file_paths:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<root-path
name="download"
path="" />
</paths>