Android 无法从资产文件夹安装apk
在我的资产文件夹中,我有一个apk文件,我的目标是在单击按钮时安装apk。我编写了一个函数,可以读取apk并生成文件,但无法安装。下面是一个我的函数Android 无法从资产文件夹安装apk,android,android-intent,android-install-apk,Android,Android Intent,Android Install Apk,在我的资产文件夹中,我有一个apk文件,我的目标是在单击按钮时安装apk。我编写了一个函数,可以读取apk并生成文件,但无法安装。下面是一个我的函数 private File prepareApk(String assetName) { byte[] buffer = new byte[8192]; InputStream is = null; FileOutputStream fout = null; try { is = getAssets()
private File prepareApk(String assetName) {
byte[] buffer = new byte[8192];
InputStream is = null;
FileOutputStream fout = null;
try {
is = getAssets().open(assetName);
fout = openFileOutput("tmp.apk", Context.MODE_PRIVATE);
int n;
while ((n=is.read(buffer)) >= 0) {
fout.write(buffer, 0, n);
}
} catch (IOException e) {
Log.i("InstallApk", "Failed transferring", e);
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fout != null) {
fout.close();
}
} catch (IOException e) {
}
}
return getFileStreamPath("tmp.apk");
}
我这样调用这个函数
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(Uri.fromFile(prepareApk("myapk.apk")));
startActivity(intent);
没有异常,没有警告,只是无法安装。这是一个my gradle文件源
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.mypackage.music"
minSdkVersion 19
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
}
我怎样才能解决我的问题?谢谢其他应用程序(包括安装程序)无法访问您应用程序的内部存储部分。另外,在Android 7.0+上,您将因
FileUriExposedException
而崩溃
在Android 7.0+上,您需要使用FileProvider
来提供文件,使用FileProvider.getUriForFile()
将Uri
放入您的意图中
在Android 6.0及更早版本上,您必须将文件保存到外部存储(例如,getExternalCacheDir()
)。谢谢您的关注,但是否可以使用fileProvider从资产文件夹中读取我的apk文件@CommonsWare@BekaKK:“但是可以使用fileProvider从资产文件夹读取我的apk文件吗?”--不,对不起,不过。我没有在您的用例中尝试过它,因为将APK封装在APK中充其量是不寻常的。在您的选择中,我如何从android 8或更低版本的资产文件夹安装apk@CommonsWare@BekaKK:使用您现有的方法,如我在回答中所述进行修改。我共享了几乎所有的源代码,new能否告诉我如何在源代码中使用fileProvider?@公用软件