Android7.0之前的跳转
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri ,"application/vnd.android.package-archive");
startActivity(intent);
Android7.0的跳转
要在AndroidManifest.xml中定义FileProvider
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="包名.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_provider_path" />
</provider>
file_provider_path为调用的资源文件。
需在AndroidManifest.xml的同级目录创建一个xml文件夹,然后在里面创建一个xml文件,文件名随意。
根据自己的需求在file_provider_path.xml文件里面写相应的。
provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!--external-path 对应 Environment.getExternalStorageDirectory()-->
<external-path name="name" path="." />
<!--files-path对应Context.getFilesDir()-->
<files-path name="name" path="." />
<!--cache-path对应Context.getCacheDir()-->
<cache-path name="name" path="." />
<!--external-files-path对Context#getExternalFilesDir(String) Context.getExternalFilesDir(null)-->
<external-files-path name="name" path="path" />
<!--external-cache-path对应Context.getExternalCacheDir()-->
<external-cache-path name="name" path="path" />
<!--cache-path对应Context.getExternalMediaDirs()(API21+)-->
<external-media-path name="name" path="path" />
</paths>
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
uri=FileProvider.getUriForFile(this,"项目包名.fileprovider",file);
}else{
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
uri = Uri.fromFile(file);
}
intent.setDataAndType(uri ,"application/vnd.android.package-archive");
startActivity(intent);
Android8.0,9.0的跳转
代码和7.0的一样只不过要在AndroidManifest.xml文件中添加
//申请未知来源权限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />