Download files in Android-DownLoadManager
In android development, file downloading functions, such as app version updates, are often used. After api level 9, the android system provides us with the DownLoadManager class, which is a system service provided by android, through which we can download files. The entire download process is handed over to the system, so we do not need to handle it too much.
The API documentation shows that DownLoadManager contains two internal classes:
DownLoadManager. Query: Used to Query download information.
DownLoadManager. Request: Mainly used to initiate a download Request.
| Ii. function implementation |
First, let's take a look at DownLoadManager. Request, which encapsulates all the information required for a download Request. Through the constructor, We can initialize a request object. when constructing the object, we need to input the download object address.
DownloadManager.Request request = new DownloadManager.Request(Uri.parse());
After constructing an object, we can set some attributes for the request:
AddRequestHeader (String header, String value): add the http header information of the network download request allowScanningByMediaScanner (): Used to set whether to allow this MediaScanner scan. SetAllowedNetworkTypes (int flags): sets the network type used for download. By default, any network can be downloaded. The network constants are NETWORK_BLUETOOTH.
,NETWORK_MOBILE
,NETWORK_WIFI
.SetAllowedOverRoaming (Boolean allowed): Used to set whether to download seticationicationvisibility (int visibility) in roaming state: Used to set seticationicationvisibility (CharSequence) in the status bar during download ): setDescription (CharSequence): setDestinationInExternalFilesDir, setDestinationInExternalPublicDir, and setDestinationUri are used to set the path for storing the downloaded file. Note that if you store the downloaded file in the default path, in case of insufficient space, the system will delete the file. Therefore, it is necessary to use the above method to set the file storage directory.
The code for creating a Request object is as follows:
DownloadManager. request request = new DownloadManager. request (Uri. parse (http://gdown.baidu.com/data/wisegame/55dc62995fe9ba82/jinritoutiao_448.apk); // sets the network in which requests are downloaded. setAllowedNetworkTypes (Request. NETWORK_WIFI); // set the notification bar title request. setNotificationVisibility (Request. VISIBILITY_VISIBLE); request. setTitle (download); request. setDescription (toutiao.com is being downloaded); request. setAllowedOverRoaming (false); // set the file storage directory request. setDestinationInExternalFilesDir (this, Environment. DIRECTORY_DOWNLOADS, mydown );
After obtaining the system service, call the enqueue method of the downloadmanager object for download. This method returns a number to indicate the download task:
downManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);id= downManager.enqueue(request);
To cancel the download, you can call the remove Method to delete the download task and downloaded files at the same time:
downManager.remove(id);
When the file download is complete, we often need to perform subsequent operations, such as apk. How can we directly display and install the file? How can we listen to the file when it has been downloaded? When the file is completed, DownLoadManager sends a broadcast whose action is ACTION_DOWNLOAD_COMPLETE. We only need to register a broadcast receiver for processing:
Private class DownLoadCompleteReceiver extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {if (intent. getAction (). equals (DownloadManager. ACTION_DOWNLOAD_COMPLETE) {long id = intent. getLongExtra (DownloadManager. EXTRA_DOWNLOAD_ID,-1); Toast. makeText (MainActivity. this, number: + id + the download task has been completed !, Toast. LENGTH_SHORT ). show ();} else if (intent. getAction (). equals (DownloadManager. action_icationication_clicked) {Toast. makeText (MainActivity. this, don't be blind !!!, Toast. LENGTH_SHORT). show ();}}}
DownManager saves and manages all current tasks. How can we obtain this information? The DownManager. Query object is used at this time. With this object, we can Query all download task information.
SetFilterById (long... ids): queries the download task information by task id.
SetFilterByStatus (int flags): queries the download Task Based on the download status.
The usage is as follows:
private void queryDownTask(DownloadManager downManager,int status) { DownloadManager.Query query = new DownloadManager.Query(); query.setFilterByStatus(status); Cursor cursor= downManager.query(query); while(cursor.moveToNext()){ String downId= cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_ID)); String title = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE)); String address = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); //String statuss = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)); String size= cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); String sizeTotal = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); Map
map = new HashMap
(); map.put(downid, downId); map.put(title, title); map.put(address, address); map.put(status, sizeTotal+:+size); this.data.add(map); } cursor.close(); }