Android webview downloadmanager File Download Management

Source: Internet
Author: User

I. Downloadmanager class description:

A download management class has been added since Android 2.3. You can find Android. App. downloadmanager In the SDK documentation. The download management class can process multiple HTTP download tasks for a long time. The client only needs to provide the requested URI and the location where the target file is stored, download management uses an aidl server, so it can be executed in the background with peace of mind. At the same time, the instantiation method needs to use getsystemservice (context. download_service), android123 again reminds users who use API level 9 to easily download files on the Android platform through the new API.

The downloadmanager class provides the following methods for processing,

Java code
  1. Long enqueue (downloadmanager. Request request) // store a new download item in the queue
  2. Parcelfiledescriptor opendownloadedfile (long ID) // open a downloaded file for reading. The long ID in the parameter is a record in a provider.
  3. Cursor query (downloadmanager. query) // queries a download and returns a cursor
  4. Int remove (long... IDs) // cancel the download and remove these items from the download management.

We can see that the provided methods are relatively simple, and the operations are encapsulated into a provider database for addition, query, and removal. However, for details about query and addition tasks, let's take a look at downloadmanager. request class and downloadmanager. query Class.

1. downloadmanager. Request class members and definition Java code

  1. Downloadmanager. request addrequestheader (string header, string value) // Add an HTTP request header. For these two parameters, the android development network provides a small example, for example, the User-Agent value can be android123 or Windows XP, and so on, mainly to provide the server with an identifier.
  2. Downloadmanager. request setallowednetworktypes (INT flags) // you can specify the network type that can be used. In this step, Android 2.3 performs well, currently, two definitions are available: network_mobile and network_wifi. You can download them using a mobile network or WiFi.
  3. Downloadmanager. Request setallowedoverroaming (Boolean allowed) // determines whether to allow roaming for downloads based on traffic charges.
  4. Downloadmanager. Request setdescription (charsequence description) // you can specify a description for the notification prompt displayed.
  5. Downloadmanager. Request setdestinationinexternalfilesdir (context, string dirtype, string subpath) // you can use the getexternalfilesdir () method to obtain the target from an external directory.
  6. Downloadmanager. Request setdestinationinexternalpublicdir (string dirtype, string subpath) // set the public directory of the external store, which is generally obtained through the getexternalstoragepublicdirectory () method.
  7. Downloadmanager. Request setdestinationuri (URI) // set the URI to be downloaded. It can be HTTP or FTP.
  8. Downloadmanager. Request setmimetype (string mimetype) // set the MIME type. Here we can see the server configuration. Generally, all the countries are UTF-8 encoded.
  9. Downloadmanager. Request setshowrunningnotification (Boolean show) // whether to display the download progress prompt
  10. Downloadmanager. Request settitle (charsequence title) // set the notification title
  11. Downloadmanager. Request setvisibleindownloadsui (Boolean isvisible) // you can specify whether the download management page is displayed during processing.

Of course, Google also provides a simple method to instantiate this class. This constructor is downloadmanager. Request (URI). You can simply enter a URI. The above settings use the default situation.

Ii. downloadmanager. Query Class

We can use the downloadmanager. Query Class to obtain the status of the downloaded content. This class is simple and only provides two methods. Java code

  1. Downloadmanager. query setfilterbyid (long... IDs) // filter and search by ID.
  2. Downloadmanager. query setfilterbystatus (INT flags) // you can view the status of the task.

The detailed status is defined in the Android. App. downloadmanager class. The current definition in Android 2.3 is:

Java code
  1. Int status_failed failed
  2. Int status_paused pause
  3. Int status_pending waiting to begin
  4. Int status_running is being processed
  5. Int status_successful has been downloaded successfully.

Finally, the android Development Network reminds you that the query method provided by the downloadmanager class returns a cursor object. These statuses are stored in the column_status field of the cursor.

1. the download status is broadcast. Currently, API level 9 defines the following three intent actionjava codes.

  1. Action_download_complete.
  2. Action_icationication_clicked is triggered when you click Download Management in notification.
  3. Action_view_downloads

2. For an unfinished item, we can find the column_reason field in cursor, which may have the following definitions: Java code

  1. Int error_cannot_resume cannot continue, for some other reasons.
  2. Int error_device_not_found: the external storage device is not found. For example, the SD card is not inserted.
  3. Int error_file_already_exists: the file to be downloaded already exists. android123 prompts that the download management class will not overwrite the existing file. Therefore, if you need to download the file again, delete the previous file first.
  4. Int error_file_error may cause a file error due to the SD card.
  5. Int error_http_data_error occurs during HTTP transmission.
  6. Int error_insufficient_space caused by insufficient SD card space
  7. Int error_too_many_redirects has too many redirection requests in HTTP, causing the download to fail.
  8. Int error_unhandled_http_code cannot obtain the cause of an HTTP Error. For example, the remote server does not respond.
  9. Int error_unknown unknown error type.

3. For some pause statuses, the value of the column_reason field may be defined in the following Java code:

  1. Int paused_queued_for_wifi due to mobile network data problems, wait for the WiFi connection to work and then re-enter the download queue.
  2. Int paused_unknown: unknown cause causes the pause of task download.
  3. Int paused_waiting_for_network may be unable to be downloaded because there is no network connection, waiting for available network connection to be restored ..
  4. Int paused_waiting_to_retry: the download is paused due to many reasons. Wait for a retry.

The introduction to download management downloadmanager added in Android 2.3 has basically been completely completed. If you understand the basic concepts of cursor and provider, we can see that this download management class can help us reduce a lot of unnecessary code writing.

II. Download with downloadmanager:

Public void ondownloadstart (string URL, string useragent,
String contentdisposition, string mimetype, long contentlength ){

Apputils. logd (mimetype );

// Download file
Downloadmanager = (downloadmanager) Activity
. Getsystemservice (activity. download_service ));
Request request = new request (URI. parse (URL ));

// Set Request Header, such as session
Request. addrequestheader ("accept ",
"Text/html, application/XHTML + XML, application/XML; q = 0.9, */*; q = 0.8 ");
Request. addrequestheader ("Accept-language", "En-US, en; q = 0.5 ");
Request. addrequestheader ("Accept-encoding", "gzip, deflate ");
Request. addrequestheader ("Accept-charset ",
"ISO-8859-1, UTF-8; q = 0.7, *; q = 0.7 ");
Request. addrequestheader ("cache-control", "Max-age = 0 ");

String host = "";
Try {
Host = new URL (URL). gethost ();
} Catch (malformedurlexception e ){
E. printstacktrace ();
}

String cookiestr = cookiemanager. getinstance (). getcookie (host );
If (! Apputils. isempty (cookiestr )){
Request. addrequestheader ("cookie", cookiestr + "; ACSE = 0 ");
}

// Generate filename dynamically
String filename = contentdisposition. replacefirst (
"Attachment; filename = ","");
Request. setdestinationinexternalpublicdir (
Environment. directory_downloads, filename );

Downloadmanager. enqueue (request );
}

3. Judge download finished:

         BroadcastReceiver receiver = new BroadcastReceiver() {              @Override              public void onReceive(Context context, Intent intent) {                  String action = intent.getAction();                  if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {                      long downloadId = intent.getLongExtra(                              DownloadManager.EXTRA_DOWNLOAD_ID, 0);                      Query query = new Query();                      query.setFilterById(enqueue);                      Cursor c = dm.query(query);                      if (c.moveToFirst()) {                          int columnIndex = c                                  .getColumnIndex(DownloadManager.COLUMN_STATUS);                          if (DownloadManager.STATUS_SUCCESSFUL == c                                  .getInt(columnIndex)) {                               ImageView view = (ImageView) findViewById(R.id.imageView1);                              String uriString = c                                      .getString(c                                              .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));                              view.setImageURI(Uri.parse(uriString));                          }                      }                  }              }          };           registerReceiver(receiver, new IntentFilter(                  DownloadManager.ACTION_DOWNLOAD_COMPLETE));

4. Obtain the download history list of the system:

Intent I = new intent (downloadmanager. action_view_downloads );
Startactivity (I );

5. Obtain the downloaded file and open the file:

Protected string getdownloadedfilename (){

String filename = "";

Downloadmanager = (downloadmanager) Activity
. Getsystemservice (activity. download_service );
Downloadmanager. query = new downloadmanager. Query ();
Query. setfilterbystatus (downloadmanager. status_successful );

Cursor c = downloadmanager. Query (query );
If (C. movetofirst ()){
Filename = C. getstring (C
. Getcolumnindex (downloadmanager. column_title ));
}

Return filename;
}

Public void openfilefromsdcard (string filestr, string mimetype ){
Intent intent = new intent ();
Intent. setaction (Android. content. Intent. action_view );
File file = new file (filestr );
Intent. setdataandtype (URI. fromfile (file), mimetype );
Activity. startactivity (intent );
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.