【step1】在res文件夹中创建xml文件夹,创建 provider_paths.xml,内容如下
<?xml version="1.0" encoding="utf-8"?>
<resources>
<paths>
<!-- <!–相当于Context.getFilesDir() + /path/–>
<files-path name="name" path="path" />
<!– 物理路径相当于Context.getCacheDir() + /path/–>
<cache-path name="name" path="path" />
<!–物理路径相当于Environment.getExternalStorageDirectory() + /path/–>
<external-path name="name" path="path" />
<!– 物理路径相当于Context.getExternalFilesDir(String) + /path/–>
<external-files-path name="name" path="path" />
<!– 物理路径相当于Context.getExternalCacheDir() + /path/–>
<external-cache-path name="name" path="path" />-->
<external-path name="files_root" path="storage/emulated/" />
<external-path name="external_files" path="."/>
</paths>
</resources>
【step2】在Mainifest.xml中添加如下内容:
<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>
还要配置SD卡读写权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
【step3】安装核心代码如下(这里使用了RxPermissions动态权限申请框架):
rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
.subscribe(granted -> {
if (granted) {
install();
} else {
Toast.makeText(MainActivity.this, "拒绝了相关权限", Toast.LENGTH_SHORT).show();
}
});
private void install() {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
File file = new File(path, "app.apk");
Log.e("tag", path);
Intent intent = new Intent(Intent.ACTION_VIEW);
// 判断版本大于等于7.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Log.e("tag", "---1111->>" + file.getPath());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 给目标应用一个临时授权
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Uri data = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider", file);
intent.setDataAndType(data, "application/vnd.android.package-archive");
} else {
Log.e("tag", "--2222-->>");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//intent.setDataAndType(Uri.parse("file://" + path), "application/vnd.android.package-archive");
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
startActivity(intent);
}
大功告成!!!
网友评论