Android Learning Note (46): Internet communications-File download

Source: Internet
Author: User

The introduction of Downloadmanager in Android 2.3 can handle complex file downloads, including checking whether a user has data connections (WiFi or mobile data) when the user moves from a data connection to a disconnected place (for example, leaving WiFi or 3G Data access point) to ensure that the device remains awake during the download process. Downloadmanager can handle HTTP URLs, but cannot handle HTTPS (SSL) URLs.

Set license for download file conditions

In this example, you will learn to download files from the Internet via Downloadmanager and store them on an external storage media SD card. There are the following needs to note:

    1. Since versions prior to 2.3 are not supported, the minimum version must be set to Android2.3 or higher.
    2. In the simulator, we need to make sure that the SD card is set, as shown in the image on the right.
    3. The program has access to the Internet and external storage and is set in Androidmanifest.xml:

      <uses-permission android:name= "android.permission.INTERNET"/>
      <uses-permission android:name= "android.permission.WRITE_EXTERNAL_STORAGE"/>
      <application>
      ....
      </application>

Design of Small Program

The specific XML file is omitted. The layout is simply divided into 3 buttons, such as the right, the first button setting android:onclick= "Startdownload", that is, the trigger Startdownload () method, which is used to request the download of a file. The second button triggers QueryStatus () and disabled, clicking on the status query that triggers the download. The third button triggers Viewlog (), which invokes the system-provided Downloadmanager activity to view the historical download situation.

Request File Download

PrivateDownloadmanagerMGR = NULL;
Private long lastdownloadid = 0;

protected void OnCreate (Bundle savedinstancestate) {
... ...
Step 1: Obtain the system service and indicate that it is the download service, i.e. Downloadmanager. This kind of service of the system most of these management does not have close (), release () and so on by the system garbage collects to handle. We just need to get the objects of these services and send our request
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 external storage of the true download file, if there is no such folder, created, if any, the following will return false. Different phones with different Android versions of the SD card mount point may not be the same, so it is obtained by means of the system.
environment.getexternalstoragepublicdirectory (environment.directory_downloads). mkdir ();

Step 2: By issuing a enqueue () request to the download service, it will be placed in the download queue, which will usually trigger an immediate download and return the downloaded ID number, according to which the relevant downloads can be queried. Set the URI of the request separately, allow access to the data, allow roaming, local storage location, and set the title and description information for this download.
Lastdownloadid = Mgr.Enqueue(NewDownloadmanager.Request(URI)
.Setallowednetworktypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI)
.setallowedoverroaming(false)//The default is true, so sky-expensive roaming data charges are generated
. Settitle ("MyTest")//For information viewing
. SetDescription ("Something useful")//For information viewing
.Setdestinationinexternalpublicdir(Environment.directory_downloads, "Test.mp4"));
V.setenabled (FALSE);
Findviewbyid (r.id.c25_query). SetEnabled (True);
}

Get Download status

There will usually be a background run to constantly update the download situation, the example is how to get it, so simply click on the second button to trigger the query download status.

public void QueryStatus (View v) {
Key: Use the ID to download the management query, 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 an extract of information 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 of the download, the SD card hang point for/mnt/sdcard/we can go through the $adb shell into the simulator console for viewing. Additionally, the overall size of the fetch file is column_total_size_bytes.

# Pwd/mnt/sdcard/download
# ls-l
----rwxr-x system SDCARD_RW 6219229 2011-11-01 14:19 test.mp4

View through download management

public void Viewlog (View v) {
StartActivity (new Intent (downloadmanager.action_view_downloads));
}

Get real-time event triggering via Boardreceiver

In the example above, the first button will be restored to the enabled state after the trigger is loaded. Learn notes on Android (three or four): Talk again about intent (top)-some knowledge of getting event-triggered processing from the server via Boardreceiver.

protected void OnCreate (Bundle savedinstancestate) {
... ...
Triggered at the end of the download.
Registerreceiver(OnComplete,new Intentfilter (downloadmanager.action_download_complete));
When you click on a file that is being downloaded,
Registerreceiver(Onnotification,new Intentfilter (downloadmanager.action_notification_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 already been downloaded, the second time is no longer downloaded. In addition, because Downloadmanager belongs to the system service, not only your app can be called, that is, the contents of the list above is global, may not be part of your app in the download, which will confuse users, in request requests, We can block it with Setvisibleindownloadsui (false).

Traditional File Download method

Ownloadmanager Service requires Android version 2.3 or more, if the conditions are not met, you can take the network file stream to handle the way, the following steps:

    1. Build a HttpURLConnection object that can be obtained through the OpenConnection () method of the URL object, for example: httpurlconnection urlconn = (httpurlconnection) Url.openconnection ();
    2. Gets a InputStream object: Urlconn.getinputstream ().

With InputStream, the rest is Java's standard I/O operations.

Attention

for Internet access, do not re-apply the main thread, but should be processed in the background thread Httpclient,httpurlconnection and other Internet access APIs. Android Learning Note (four or five): an example of Internet communication-httpclient, XML parsing (web) is simply a small example of how to use the relevant usage.

RELATED links: My Andriod development related articles

Android Learning Note (46): Internet communications-File download

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.