In my assets folder,I have one apk file,My goal is to install apk in button click.I wrote a function to can read apk and generate File and can not install it.Here is a my function
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");
}
I call this function like this
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(Uri.fromFile(prepareApk("myapk.apk")));
startActivity(intent);
No exceptions,no warnings,just can not install it.Here is a my gradle file source
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'
} How I can solve my problem? thanks
Other apps — including the installer — have no access to your app's portion of internal storage. Plus, on Android 7.0+, you will crash with a FileUriExposedException
.
On Android 7.0+, you will need to use FileProvider
to serve up the file, using FileProvider.getUriForFile()
for the Uri
to put in your Intent
.
On Android 6.0 and earlier, you will have to save your file to external storage (eg, getExternalCacheDir()
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.