[英]How to install APK file from assets folder?
I want to install an APK file from the Assets folder.我想从 Assets 文件夹中安装一个 APK 文件。 I use the method: Copy the Apk file from the Assets folder to the folder of internal storage.
我使用方法:将Apk文件从Assets文件夹复制到内部存储文件夹。 Then install the APK file.
然后安装APK文件。 But I got this error:
但我得到了这个错误:
`android.os.FileUriExposedException: file:///sdcard/myapk.apk exposed beyond app through
Intent.getData()`
MainActivity.java: MainActivity.java:
btn2 = findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
rarPath = "test.apk";
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(rarPath);
out = new FileOutputStream("/sdcard/myapk.apk");
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/sdcard/myapk.apk")),
"application/vnd.android.package-archive");
startActivity(intent);
} catch(Exception e) { e.printStackTrace();
Toast.makeText(getApplicationContext(),"Error !",Toast.LENGTH_LONG).show();}
}
});
}
If targetSdkVersion is higher than 24, then FileProvider is used to grant access.如果 targetSdkVersion 高于 24,则使用 FileProvider 授予访问权限。
Create an xml file(Path: res\xml) provider_paths.xml创建 xml 文件(路径: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>
Add a Provider in AndroidManifest.xml在AndroidManifest.xml中添加一个Provider
<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>
If you are using androidx, the FileProvider path should be:如果您使用的是 androidx,则 FileProvider 路径应为:
android:name="androidx.core.content.FileProvider"
and replace并更换
Uri uri = Uri.fromFile(yourPath);
to至
Uri uri = FileProvider.getUriForFile(MainActivity.this,BuildConfig.APPLICATION_ID + ".provider",yourPath);
Edit: While you're including the URI with an Intent make sure to add below line:编辑:当您包含带有 Intent 的 URI 时,请确保添加以下行:
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.