Skip to content

Instantly share code, notes, and snippets.

@emaillenin
Created December 11, 2016 04:54
Show Gist options
  • Save emaillenin/9a0fea5a6924ddb23b8dd620392e745f to your computer and use it in GitHub Desktop.
Save emaillenin/9a0fea5a6924ddb23b8dd620392e745f to your computer and use it in GitHub Desktop.
Download APK using DownloadManager and start installation automatically - Android 7.0 Nougat compatible
public void downloadUpdate() {
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = "your_app.apk";
destination += fileName;
final Uri uri = Uri.parse("file://" + destination);
File file = new File(destination);
if (file.exists())
file.delete();
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(getIntent().getStringExtra("url")));
request.setDestinationUri(uri);
dm.enqueue(request);
final String finalDestination = destination;
final BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri contentUri = FileProvider.getUriForFile(ctxt, BuildConfig.APPLICATION_ID + ".provider", new File(finalDestination));
Intent openFileIntent = new Intent(Intent.ACTION_VIEW);
openFileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
openFileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
openFileIntent.setData(contentUri);
startActivity(openFileIntent);
unregisterReceiver(this);
finish();
} else {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setDataAndType(uri,
"application/vnd.android.package-archive");
startActivity(install);
unregisterReceiver(this);
finish();
}
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
@utahemre
Copy link

Karlos said the solution of your problem. You have to add REQUEST_INSTALL_PACKAGES to your androidManifest.xml. Without this permission, .apk files are not clickable.

@qureshiayaz29
Copy link

android Q does not expose getExternalStoragePublicDirectory() due to security concern, so it is requested to replace 'getExternalStoragePublicDirectory()' with 'getExternalFilesDir()' for new/old version of android for downloading (i.e. writing) and reading file

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment