Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to install .apk programmly on Android Q?

I'm developing an app and want to support Android Q. And I'm using the Android Emulator. I have downloaded an apk file in the path.

/storage/emulated/0/Android/data/<package-name>/files/download/xxxxxx.apk

I install the apk like this:

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", new File(apkPath));
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");        
startActivity(intent);

The above code is working fine before Android Q. But on Android Q, I only can get the file uri

content://<package-name>.fileprovider/my_downloads/xxxxxx.apk

, but the installation screen is not shown when sending the intent. I need someone's help. Thanks very much!

like image 576
Fen Li Avatar asked Nov 25 '25 19:11

Fen Li


1 Answers

The problem is about installing unknown app after Android O. I should use the permission:

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>

and check the permission before installation:

getPackageManager().canRequestPackageInstalls()

If the permission has been granded, it's ok to continue the installation. Otherwise, we should send the intent to open the permission page:

Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, REQUEST_INSTALL_PERMISSION);

And we can handle the result in onActivityResult.

like image 195
Fen Li Avatar answered Nov 27 '25 09:11

Fen Li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!