Android6.0以下
public static void installNewPackage(Context context, String path) {
if (StringUtils.isNull(path)) {
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
context.startActivity(intent);
}
Android6.0及以上
先要配置AndroidManifest.xml
1.Application節(jié)點添加如下代碼
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
2.在資源文件夾res下新建xml目錄忍抽,新建provider_paths.xml文件蜒秤,文件內(nèi)容如下
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
3.調(diào)用代碼
private static void openFile(File var0, Context var1) {
Intent var2 = new Intent();
var2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
var2.setAction(Intent.ACTION_VIEW);
Uri uriForFile = FileProvider.getUriForFile(var1, var1.getApplicationContext().getPackageName() + ".provider", var0);
var2.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
var2.setDataAndType(uriForFile, var1.getContentResolver().getType(uriForFile));
try {
var1.startActivity(var2);
} catch (Exception var5) {
var5.printStackTrace();
Toast.makeText(var1, "沒有找到打開此類文件的程序", Toast.LENGTH_SHORT).show();
}
}