Download A File In Background Without Opening Browser With Intent
try { String url = 'MY URL' i = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); view.openDownloadIntent(i); // startsActivity } catch (NullPointerException e) { vi
Solution 1:
You can use simply DownloadManager
for this task,
The DownloadManager is a system service that handles long-running HTTP downloads. Clients may request that a URI be downloaded to a particular destination file. The download manager will conduct the download in the background, taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots.
For example,
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle("Downloading..."); //set title for notification in status_bar
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //flag for if you want to show notification in status or not
//String nameOfFile = "YourFileName.pdf"; //if you want to give file_name manually
String nameOfFile = URLUtil.guessFileName(url, null, MimeTypeMap.getFileExtensionFromUrl(url)); //fetching name of file and type from server
File f = new File(Environment.getExternalStorageDirectory() + "/" + yourAppFolder); // location, where to download file in external directory
if (!f.exists()) {
f.mkdirs();
}
request.setDestinationInExternalPublicDir(yourAppFolder, nameOfFile);
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
downloadManager.enqueue(request);
And you also have to add WRITE_EXTERNAL_STORAGE
permission in your AndroidManifest
file that is,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Post a Comment for "Download A File In Background Without Opening Browser With Intent"