Qianfeng-android-day07-asynctask Basic Learning: "The illusion of countless scenes of mortals"

Source: Internet
Author: User

Asynchronous Task Asynctask and JSON parsing First, Asynctask: (a), relevant knowledge review:

1, the development of Android applications must adhere to the principle of single-threaded model:

Android UI actions are not thread-safe, and they must be executed in the UI thread.

2, the single-threaded model always have to remember the two rules:

1). Do not block the UI thread;

2). Make sure that the Android UI controls are accessible only in the UI thread.

when a program starts for the first time, Android will start a corresponding main thread at the same time,

The main thread is mainly responsible for dealing with UI-related events, such as user key events, User touch screen events, and screen drawing events, and distributing related events to corresponding components for processing. So the main thread is often called the UI thread.

3, Android4.0 or more in the version , access to the network is not allowed in the main thread. Programs that involve network operations are generally required to open a new thread to complete network access. However, after you have obtained the page data, you cannot return the data to the UI interface. Because the child thread (Worker thread) does not have direct access to the members of the UI thread, that is, there is no way to manipulate the content on the UI interface, and if the operation throws an exception: Calledfromwrongthreadexception.

In fact,Android provides several ways to access the UI thread in other threads:

Activity.runonuithread (Runnable)

View.post (Runnable)

View.postdelayed (Runnable, long)

Handler messaging mechanism (explained in subsequent courses)

These classes or methods make the code complex and difficult to understand. To solve this problem,Android 1.5 provides a tool class: Asynctask, which makes it easier to create tasks that run interactively with the user interface for long periods of time. Asynctask is more lightweight and works with simple asynchronous processing without the need for threading and handler.

(ii), Asynctask's code implementation:

1 , Asynctask is an abstract class. Asynctask defines three generic type params,progress and result.

The Params is the input parameter that initiates the task execution, such as the URL of the HTTP request. generally with string type;

Progress the percentage of background task execution. General use of integer type;

Result the results of the final return of the task in the background, usually with byte[] or string.

2 , The implementation of Asynctask is divided into four steps, each of which corresponds to a callback method (a method that is automatically called by the application), and what developers need to do is implement these methods.

1) Define the subclass of the Asynctask;

2) Implement the methods defined in Asynctask: (can be fully implemented, or only a subset of them can be implemented)

OnPreExecute (), the method is called by the UI thread before performing the actual background operation. You can do some preparatory work in this method, such as displaying a progress bar on the interface.

Doinbackground (Params ...), which executes immediately after the OnPreExecute method executes, runs in the background thread. This will be primarily responsible for performing time-consuming background computations. You can call the Publishprogress method to update the real-time task progress. The method is an abstract method that the subclass must implement.

Onprogressupdate (Progress ...), after the Publishprogress method is called, the UI thread will invoke this method to show the progress of the task on the interface, for example, by displaying it through a progress bar.

OnPostExecute (Result), after Doinbackground execution completes, the OnPostExecute method is called by the UI thread, and the results of the background are passed through the method to the UI thread.

(iii), the asynchronous task of increasing the progress bar: 1, Production ideas:

Displays the progress dialog box in onpreexecute ();

The progress is calculated in the Doinbackground () method, and the progress data is released at any time by calling the Publishprogress () method in the while loop.

the calculation formula for the progress data:publishprogress ((int) ((Count/(double) length) * 100)), where count is the length of the file currently loaded and length is the total length of the file;

in the OnPostExecute () method, make the progress bar disappear.

2. Core code:

class Downloadimage extends asynctask<string, Integer, byte[]> {

Private TextView TV;

Private ProgressBar PB;

@Override

protected void onprogressupdate (Integer ... values) {

values are determined by publishprogress (); method passed over

if (Values.length > 0) {

Show current progress percentage

Tv.settext (Values[0] + "%");

set The progress of ProgressBar

Pb.setprogress (Values[0]);

}

}

@Override

protected void OnPreExecute () {

TV = (TextView) Findviewbyid (r.id. TV);

PB = (ProgressBar) Findviewbyid (r.id. PB);

}

@Override

protected void onpostexecute (byte[] result) {

Compiles a byte array into bitmap

Bitmap Bitmap = bitmapfactory. Decodebytearray (result, 0, result.length);

ImageView IV = (ImageView) Findviewbyid (r.id. IV);

set a picture for ImageView

Iv.setimagebitmap (bitmap);

}

@Override

protected byte [] Doinbackground (String ... params) {

HttpURLConnection con = null;

Bytearrayoutputstream BAOs = new bytearrayoutputstream ();

InputStream is = null;

Try {

URL url = new URL (params[0]);

Open Connection

Con = (httpurlconnection) url.openconnection ();

setting the time-out period

Con.setconnecttimeout (5 * 1000);

Connection

Con.connect ();

get the total number of bytes in the picture size

double totalcount = Con.getcontentlength ();

the number of bytes currently downloaded

int count = 0;

Log. D ("Qianfeng", "TotalCount:" + totalcount);

parsing InputStream

if (Con.getresponsecode () = = 200) {

is = Con.getinputstream ();

int len = 0;

byte [] buf = new byte[1024];

while (len = Is.read (BUF))! =-1) {

Baos.write (buf, 0, Len);

Baos.flush ();

Count + = Len;

Log. D ("Qianfeng", Count + "/" + TotalCount);

Publishprogress ((int) ((count/totalcount) * 100));

}

}

} catch (Malformedurlexception e) {

E.printstacktrace ();

} catch (IOException e) {

E.printstacktrace ();

} finally {

if (Con! = null) {

Con.disconnect ();

}

if (IS! = null) {

Try {

Is.close ();

} catch (IOException e) {

E.printstacktrace ();

}

}

}

return Baos.tobytearray ();

}

}

Second, JSON: (a), concept:

JSON (JavaScript Object notation), is a lightweight data storage and exchange format. It is completely language-independent in text format. JSON is easy to read, write, and easy to machine parse and generate.

(ii), JSON basic format:

1. Key-value pair Object format: Surround with "{}"

2. Array format: Surround with "[]".

(iii), JSON PK XML:

1. JSON and XML are comparable in readability and extensibility;

2, decoding difficulty on the view, JSON more convenient and concise;

3. JSON is worse than XML in descriptive data;

4, the application of JSON to realize the function is much faster than XML.

(iv), JSON parsing principle:

1, see {}, create Jsonobject object;

2, see [], create Jsonarray object;

3, see Jsonarray, to For loop traversal.

Qianfeng-android-day07-asynctask Basic Learning: "The illusion of countless scenes of mortals"

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.