由于android7.0应用内共享文件以及8.0需要应用安装未知来源的权限,所以需要适配7.0以及8.0;
1.首先在res文件夹里创建xml文件夹,然后添加file_paths.xml文件
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<root-path name="root" path="" />
<external-path name="external_storage_root" path="." />
<external-path name="external_storage_download" path="Download" />
</paths>
2.manifest文件需要添加添加下载权限,网络权限以及其他权限,最重要的是要添加安装位置来源的权限:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
3.给manifest添加fileprovider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="你的包名.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
4.调用安装程序
public static void installApp(Context pContext, File pFile){
if (null == pFile)
return;
if (!pFile.exists())
return;
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
uri = FileProvider.getUriForFile(pContext, pContext.getPackageName() + ".fileProvider", pFile);
}else {
uri = Uri.fromFile(pFile);
}
intent.setDataAndType(uri, "application/vnd.android.package-archive");
pContext.startActivity(intent);
}
到这里也就大功告成了;