Java – check that the download manager has downloaded the file
How do I check if a file has been downloaded and run its installation? I have a code:
public void downloadUpdate(String url){ DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setDescription("Downloading..."); request.setTitle("App Update"); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); String name = URLUtil.guessFileName(url,null,MimeTypeMap.getFileExtensionFromUrl(url)); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,name); DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); manager.enqueue(request); }
Solution
To check whether the download manager has downloaded the file, you must implement broadcastreceiver
@Override public void onReceive(Context context,Intent intent) { String action = intent.getAction(); if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) { DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,0)); DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); Cursor cursor = manager.query(query); if (cursor.moveToFirst()) { if (cursor.getCount() > 0) { int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)); if (status == DownloadManager.STATUS_SUCCESSFUL) { String file = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME)); // So something here on success } else { int message = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON)); // So something here on Failed. } } } } }
However, I'm not sure if you can install APK programmatically For security reasons, I don't think you can For application updates, I think you should use Google version control When you redeploy the application with a different version number, the user should be able to update automatically (unless the user closes it on Google play) I hope this will help
to update
You don't need to call the method I mentioned You only need to declare the broadcast receiver in the manifest XML file, and the downloadmanager will be called when the download is complete The XML looks like this:
<receiver android:name=".BroadcastReceiver" android:enabled="true" android:exported="true" > <intent-filter> <action android:name="android.intent.action.DOWNLOAD_COMPLETE" /> <action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED" /> </intent-filter> </receiver>