Created
December 11, 2016 04:54
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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