Android Study Notes (SAT): Internet communication-File Download

Source: Internet
Author: User

DownloadManager is introduced in Android 2.3 to process complex file downloads, including checking whether users have data connections (WIFI or mobile data ), when a user moves from a data-connected location to a non-connected location (for example, an access point that leaves Wi-Fi or 3G data), ensure that the device remains awake during the download process. DownloadManager can process HTTP URLs, but cannot process HTTPS (SSL) URLs.

Set File Download Conditions

In this example, we will learn how to download files from the Internet through DownloadManager and store them on the SD card of the external storage media. Note the following:

  1. Because versions earlier than 2.3 are not supported, you must set the minimum version to Android2.3 or later.
  2. In the simulator, make sure that the SD card has been set, as shown in the right figure.
  3. The program has Internet and External Storage Access Permissions. In Androidmanifest. xml, set:

    <Uses-permission android: name ="Android. permission. INTERNET"/>
    <Uses-permission android: name ="Android. permission. WRITE_EXTERNAL_STORAGE"/>
    <Application>
    ....
    </Application>

Small Program Design

The specific xml file is omitted. The layout is simply divided into three buttons, such as the right figure. The first button sets android: onClick = "startDownload", that is, the startDownload () method is triggered after the button is clicked to request the download of the file. The second button triggers queryStatus (), disabled, and click to trigger the download status query. The third button triggers viewLog () and calls the DownloadManager Activity provided by the system to view historical downloads.

Request File Download

PrivateDownloadManagerMgr = null;
Private long lastDownloadId = 0;

Protected void onCreate (Bundle savedInstanceState ){
... ...
// Step 1: Obtain the system service and specify the download service, that is, downloadmanager. Most of the management of such services in the system is not close (), and release () is collected by garbage. We only need to get the objects of these services and send our requests.
Mgr = (downloadmanager)GetSystemService(DOWNLOAD_SERVICE);
}

Public void startdownload (view v ){
Uri uri = URI. parse ("http://commonsware.com/misc/test.mp4 ");
// The file will be stored in the download file of the External Store. If this folder is not found, create it. If yes, false is returned. The Mount Points of SD cards of different Android versions on different mobile phones may be different, so they are obtained through the system.
Environment. getExternalStoragePublicDirectory (Environment. DIRECTORY_DOWNLOADS). mkdir (); 

// Step 2: By sending an enqueue () request to the download service, it will be placed in the download queue. Generally, the download will be triggered immediately and the download ID will be returned. According to this ID, you can query the download information. Set the request URI, the allowed data access method, whether to allow roaming, the location of local storage, and set the title and description for this download.
LastDownloadId = mgr.Enqueue(NewDownloadManager.Request(Uri)
.SetAllowedNetworkTypes(DownloadManager. Request. NETWORK_MOBILE | DownloadManager. Request. NETWORK_WIFI)
.SetAllowedOverRoaming(False)
// The default value is true, so the daily roaming data fee is generated.
. SetTitle ("MyTest") // used for information viewing
. SetDescription ("Something Useful ")
// View information
.SetDestinationInExternalPublicDir(Environment. DIRECTORY_DOWNLOADS, "test.mp4 "));
V. setEnabled (false );
FindViewById (R. id. c25_query). setEnabled (true );
}

Get Download Status

There is usually a background running to continuously update the download, the example is to obtain, so simply by clicking the second button to trigger query download status.

Public void queryStatus (View v ){
// Key: query the download status through the ID and return a cursor
Cursor c = mgr. query (new DownloadManager. Query (). setFilterById (LastDownloadId));
If (c = null ){
Toast. makeText (this, "Download not found! ", Toast. LENGTH_LONG). show ();
} Else {// The following is information extraction from the cursor
C. moveToFirst ();
Log. d (getClass (). getName (), "Column_id:" +
C. getlong (C. getcolumnindex (downloadmanager. column_id )));
Log. D (getclass (). getname (), "column_bytes_downloaded so far:" +
C. getlong (C. getcolumnindex (downloadmanager. column_bytes_downloaded_so_far )));
Log. D (getclass (). getname (), "column last modified timestamp:" +
C. getlong (C. getcolumnindex (downloadmanager. column_last_modified_timestamp )));
Log. D (getclass (). getname (), "column local URI:" +
C. getString (c. getColumnIndex (DownloadManager. COLUMN_LOCAL_URI )));
Log. d (getClass (). getName (), "Column statue:" +
C. getInt (c. getColumnIndex (DownloadManager. COLUMN_STATUS )));
Log. d (getClass (). getName (), "Column reason:" +
C. getInt (c. getColumnIndex (DownloadManager. COLUMN_REASON )));

Toast. makeText (this, statusMessage (c), Toast. LENGTH_LONG). show ();
}
}

Private String statusMessage (Cursor c ){
Switch (c. getInt (c. getColumnIndex (DownloadManager. COLUMN_STATUS ))){
Case DownloadManager. STATUS_FAILED:
Return "Download failed ";
Case DownloadManager. STATUS_PAUSED:
Return "Download paused ";
Case DownloadManager. STATUS_PENDING:
Return "Download pending ";
Case DownloadManager. STATUS_RUNNING:
Return "Download in progress! ";
Case DownloadManager. STATUS_SUCCESSFUL:
Return "Download finished ";
Default:
Return "unknown information ";
}
}

From the information, we can see the location where the download is stored. the SD card's mount point is/mnt/sdcard/We can use $ ADB
Go to the simulator console to view the shell. In addition, the total size of the obtained file is column_total_size_bytes.

# PWD/mnt/sdcard/download
# Ls-l
---- Rwxr-x system sdcard_rw 6219229 test.mp4

View through download management

Public void viewlog (view v ){
Startactivity (New Intent (DownloadManager. ACTION_VIEW_DOWNLOADS));
}

Get real-time event trigger through BoardReceiver

In the preceding example, you want to trigger the button after a download, and restore the first button to enabled. In Android Study Notes (3 and 4): Let's talk about intent (I)-some knowledge about how to get event trigger processing from the server through boardreceiver.

Protected void oncreate (bundle savedinstancestate)
{
......
// Triggered when the download is complete.
RegisterReceiver(OnComplete,New IntentFilter (DownloadManager. ACTION_DOWNLOAD_COMPLETE));
// When you click an object being downloaded,
RegisterReceiver(OnNotification, new IntentFilter (DownloadManager. action_icationication_clicked ));
}
BroadcastReceiver onComplete = new BroadcastReceiver (){
Public voidOnReceive(Context context, Intent intent ){
FindViewById (R. id. c25_start). setEnabled (true );
}
};
BroadcastReceiver onNotification = new BroadcastReceiver (){
Public voidOnReceive(Context context, Intent intent ){
Toast. makeText (context, "......", Toast. LENGTH_LONG). show ();
}
};

For DownloadManager, if the file has been downloaded, you do not need to download it again for the second time. In addition, because DownloadManager is a system service, it is not only possible for your app to call, that is, the content of the list above is global, but may not be downloaded by your app. This will confuse users, in the request, we can block it with setVisibleInDownloadsUi (false.

Traditional File Download Methods

The ownloadManager service requires Android version 2.3 or later. If the conditions are not met, you can use the method of obtaining network file streams. The specific steps are as follows:

  1. Create an HttpURLConnection object, which can be obtained through the openConnection () method of the URL object, for example, HttpURLConnection urlConn = (HttpURLConnection) url. openconnection ();
  2. Obtain an InputStream object: urlConn. getInputStream ().

With InputStream, the rest are Java standard I/O operations.

Note:

For Internet access, do not apply the main thread, but process it in the background thread.HttpClient, HttpUrlConnection, and other Internet access APIs. Android Study Notes (four or five): Internet communication-HttpClient, XML parsing (W3C) examples are just a small example to illustrate how to use.

Related Links: My Andriod development articles

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.