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节点添加如下代码
<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文件,文件内容如下
<?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.调用代码
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();
}
}