Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
969 views
Welcome To Ask or Share your Answers For Others

1 Answer

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" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...