android+安装apk报错,Android N安装apk报错:android.os.FileUriExposedException(示例代码)

StackOverflow: http://stackoverflow.com/questions/38200282/android-os-fileuriexposedexception-file-storage-emulated-0-test-txt-exposed

1.在AndroidMainifest.xml文件中添加:

android:name="android.support.v4.content.FileProvider"android:authorities="${applicationId}.provider"android:exported="false"android:grantUriPermissions="true">

android:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/provider_paths"/>

###:

authorities:app的包名.fileProvider

grantUriPermissions:true,表示授予 URI 临时访问权限

exported:false

resource:下一步添加的文件

2.在res下新建一个名为xml的文件家,再新建文件provider_paths:

name="files_root"path="Android/data/com.example.downloadapk/"/>

name="external_storage_root"path="."/>

###:

path:需要临时授权访问的路径(.代表所有路径)

name:给访问路径命名

3.安装apk文件:

/*** 安装apk文件

*

*@paramapkFile 安装包所在目录*/

private voidinstallApk(File apkFile) {

Intent intent= newIntent(Intent.ACTION_VIEW);try{

String[] command= {"chmod", "777", apkFile.toString()};

ProcessBuilder builder= newProcessBuilder(command);

builder.start();

}catch(IOException ignored) {

}if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.N) {

intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

Uri contentUri=FileProvider.getUriForFile(getApplicationContext(),

BuildConfig.APPLICATION_ID+ ".fileProvider", apkFile);

intent.setDataAndType(contentUri,"application/vnd.android.package-archive");

}else{

intent.setDataAndType(Uri.fromFile(apkFile),"application/vnd.android.package-archive");

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

}

startActivity(intent);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值