Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
980 views
in Technique[技术] by (71.8m points)

android - 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) {
    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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...