Download a file in background without opening brow

2019-08-25 04:07发布

try {

    String url = "MY URL"
    i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    view.openDownloadIntent(i); // startsActivity
}
catch (NullPointerException e) {
    view.showMissingDocumentMessage("Failed");
}

This obviously opens a browser with the URL and goes immedtiatly to a downloading task. It works, but it's interruptive and should happen in the background.

Is there another way to do this?

1条回答
forever°为你锁心
2楼-- · 2019-08-25 04:33

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" />
查看更多
登录 后发表回答