Asynctask instance Code demonstrates Android asynchronous tasks

Source: Internet
Author: User
Keywords:Android mobile embedded mobile development platform Google mobile

We have mentioned that android provides a more simple thread-based asynctask method for processing multi-task asynchronous tasks. Compared with threads, asynctask is safer for processing simple tasks, the internal implementation method uses the android handler mechanism. For common file downloads, The asynctask class can be used for processing. In the browser, the favicon of the Web server URL is downloaded.

First, android123 uses a simple download example to demonstrate the general structure of the class, as shown below:

Private class downloadfilestask extends asynctask {

Protected long doinbackground (URL... URLs ){

Int COUNT = URLs. length;

Long totalsize = 0;

For (INT I = 0; I <count; I ++ ){

Totalsize + = Downloader. downloadfile (URLs [I]);

Publishprogress (INT) (I/(float) count) 100 ));

}

Return totalsize;

}

Protected void onprogressupdate (integer... progress ){

Setprogresspercent (Progress [0]);

}

Protected void onpostexecute (long result ){

Showdialog ("downloaded" + Result + "bytes ");

}

}

Finally, run downloadfilestask(cmd.exe cute (url1, url2, url3.

Download the favicon In the android browser as follows:

Class downloadtouchicon extends asynctask {

Private Final contentresolver mcontentresolver;

Private Final cursor mcursor;

Private final string moriginalurl;

Private final string murl;

Private final string museragent;

/* Package */browseractivity mactivity;

Public downloadtouchicon (browseractivity activity, contentresolver Cr,

Cursor C, webview view) {// Constructor

Mactivity = activity;

Mcontentresolver = CR;

Mcursor = C;

Moriginalurl = view. getoriginalurl ();

Murl = view. geturl ();

Museragent = view. getsettings (). getuseragentstring ();

}

Public downloadtouchicon (contentresolver Cr, cursor C, string URL) {// construct this class

Mactivity = NULL;

Mcontentresolver = CR;

Mcursor = C;

Moriginalurl = NULL;

Murl = URL;

Museragent = NULL;

}

@ Override

Public bitmap doinbackground (string... values) {// return bitmap type

String url = values [0];

Androidhttpclient client = androidhttpclient. newinstance (museragent );

Httpget request = new httpget (URL );

Httpclientparams. setredirecting (client. getparams (), true); // handle redirection issues such as 302

Try {

Httpresponse response = client.exe cute (request );

If (response. getstatusline (). getstatuscode () = 200) {// If OK

Httpentity entity = response. getentity ();

If (entity! = NULL ){

Inputstream content = entity. getcontent (); // Save the icon to inputstream because it is binary.

If (content! = NULL ){

Bitmap icon = bitmapfactory. decodestream (// retrieves bitmap from the stream. Here we use the static method decodestream of the bitmapfactory class.

Content, null, null );

Return icon;

}

}

}

} Catch (illegalargumentexception ex ){

Request. Abort ();

} Catch (ioexception ex ){

Request. Abort ();

} Finally {

Client. Close ();

}

Return NULL;

}

@ Override

Protected void oncancelled (){

If (mcursor! = NULL ){

Mcursor. Close ();

}

}

@ Override

Public void onpostexecute (Bitmap icon ){

If (mactivity! = NULL ){

Mactivity. mtouchiconloader = NULL;

}

If (icon = NULL | mcursor = NULL | iscancelled ()){

Return;

}

The final icon is saved to the internal database of the browser. The system programs are saved in SQLite format, and browser is no exception. Because the image is binary, The Blob type of the database is stored in byte arrays.

Final bytearrayoutputstream OS = new bytearrayoutputstream ();

Icon. Compress (bitmap. compressformat. PNG, 100, OS); // compress bitmap to PNG encoding, with a quality of 100%

Contentvalues values = new contentvalues (); // construct the SQLite content object, which can be replaced by raw SQL.

Values. Put (browser. bookmarkcolumns. touch_icon, OS. tobytearray (); // write the browser. bookmarkcolumns. touch_icon field of the database

If (mcursor. movetofirst ()){

Do {

Mcontentresolver. Update (contenturis. withappendedid (browser. bookmarks_uri, mcursor. getint (0), values, null, null );

} While (mcursor. movetonext ());

}

Mcursor. Close ();

}

}

Two asynctask classes have been used to demonstrate the construction of multiple types of tasks in this android Development Network. Pay attention to the returned types, this section describes operations related to content provider, asynctask, bitmap, HTTP, and stream on the Android platform, you can easily get started with Google's mobile platform by understanding how Google implements the general architecture of the Android system.

Reference: http://mips.eefocus.com/article/10-08/1968501282623682.html

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.