Fen Li
Fen Li

Reputation: 209

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!

Upvotes: 3

Views: 1943

Answers (1)

Fen Li
Fen Li

Reputation: 209

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.

Upvotes: 3

Related Questions