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 long enqueue (DownloadManager. Request request) // store a new download item in the queue
ParcelFileDescriptor openDownloadedFile (long id) // open a downloaded file for reading. The long id in the parameter is a record in a provider.
Cursor query (DownloadManager. Query query) // queries a download and returns a Cursor
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 definitions
Java code 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.
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.
DownloadManager. Request setAllowedOverRoaming (boolean allowed) // determines whether to allow roaming for downloads based on traffic charges.
DownloadManager. Request setDescription (CharSequence description) // you can specify a description for the notification prompt displayed.
DownloadManager. Request setDestinationInExternalFilesDir (Context context, String dirType, String subPath) // you can use the getExternalFilesDir () method to obtain the target from an external directory.
DownloadManager. Request setDestinationInExternalPublicDir (String dirType, String subPath) // set the public directory of the external store, which is generally obtained through the getExternalStoragePublicDirectory () method.
DownloadManager. Request setDestinationUri (Uri uri) // set the Uri to be downloaded. It can be http or ftp.
DownloadManager. Request setMimeType (String mimeType) // set the mime type. Here we can see the server configuration. Generally, all the countries are UTF-8 encoded.
DownloadManager. Request setShowRunningNotification (boolean show) // whether to display the download progress prompt
DownloadManager. Request setTitle (CharSequence title) // set the notification title
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 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 DownloadManager. Query setFilterById (long... ids) // filter and search by id.
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 int STATUS_FAILED failed
Int STATUS_PAUSED pause
Int STATUS_PENDING waiting to begin
Int STATUS_RUNNING is being processed
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 actions.
Java code: ACTION_DOWNLOAD_COMPLETE.
Action_icationication_clicked is triggered when you click Download Management in notification.
ACTION_VIEW_DOWNLOADS
2. For an unfinished item, the COLUMN_REASON field in Cursor may have the following definitions:
The Java code int ERROR_CANNOT_RESUME cannot be continued for some other reasons.
Int ERROR_DEVICE_NOT_FOUND: the external storage device is not found. For example, the SD card is not inserted.
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.
Int ERROR_FILE_ERROR may cause a file error due to the SD card.
Int ERROR_HTTP_DATA_ERROR occurs during Http transmission.
Int ERROR_INSUFFICIENT_SPACE caused by insufficient SD card space
Int ERROR_TOO_MANY_REDIRECTS has too many redirection requests in Http, causing the download to fail.
Int ERROR_UNHANDLED_HTTP_CODE cannot obtain the cause of an http Error. For example, the remote server does not respond.
Int ERROR_UNKNOWN unknown error type.
3. For some pause statuses, the value of the COLUMN_REASON field may be defined below.
Java code 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.
Int PAUSED_UNKNOWN: unknown cause causes the pause of task download.
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 ..
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 = (DownloadManager) activity
. GetSystemService (Activity. DOWNLOAD_SERVICE ));
Request request = new Request (Uri. parse (url ));
// Set request header, such as session and other www.2cto.com
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 ER = 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 = (DownloadManager) activity
. GetSystemService (Activity. DOWNLOAD_SERVICE );
DownloadManager. Query 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 );
}
From fhy_2008