Android Development Notes: Deep understanding of multithreaded Asynctask_android

Source: Internet
Author: User
Tags java se
Understanding Asynctask
Asynctask is a class of Android 1.5 Cubake to implement asynchronous operations, which can only be multithreaded asynchronously using thread in the Java SE Library, Asynctask is the Android platform's own asynchronous tool, Integrated with the Android platform features, making asynchronous operations more secure, convenient and practical. In essence it is also an encapsulation of thread in the Java SE Library, plus platform-related features, so it is highly recommended for all multithreaded asynchrony, because it is also integrated into the Android platform's features, more secure and more efficient.
Asynctask can easily perform asynchronous operations (Doinbackground), and can easily communicate with the main thread, which itself has good encapsulation, can be canceled (cancel). As for the use of asynctask, the documentation is very clear, and the following is a direct example.
Instance
This example uses Asynctask to download pictures on the network while displaying progress, downloading the image and updating the UI.
Copy Code code as follows:

Package com.hilton.effectiveandroid.concurrent;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.net.HttpURLConnection;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import android.app.Activity;
Import Android.content.Context;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.os.AsyncTask;
Import Android.os.Bundle;
Import Android.os.SystemClock;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.ImageView;
Import Android.widget.ProgressBar;
Import COM.HILTON.EFFECTIVEANDROID.R;
/*
* Asynctask cannot is reused, i.e. if you have executed one asynctask, you must discard it, you cannot execute it again.
* If you try to execute a executed asynctask, you'll get "Java.lang.IllegalStateException:Cannot execute task:the Tas K is already running "
* In this demo, if you click ' Get the image ' button twice at no time, you'll receive ' illegalstateexception '.
* About cancellation:
* Can call Asynctask#cancel () in any time during asynctask executing, but the ' result is onpostexecute () ' not called After
* Doinbackground () finishes, which means Doinbackground () is not stopped. Asynctask#iscancelled () returns True after Cancel () getting
* Called, so if you are want to really cancel the task, i.e. stop Doinbackground (), for must check the return value of Iscance Lled () in
* Doinbackground, when there are loops in Doinbackground.
* This is the same to Java threading, in which is no effective way to stop a running thread, only way to does is set a flag To Thread, and check
* The flag every time in Thread#run (), if flag is set, run () aborts.
*/
public class Asynctaskdemoactivity extends activity {
private static final String ImageUrl = "http://i1.cqnews.net/sports/attachement/jpg/site82/2011-10-01/ 2960950278670008721.jpg ";
Private ProgressBar Mprogressbar;
Private ImageView Mimageview;
Private Button mgetimage;
Private Button Mabort;

@Override
public void OnCreate (Bundle icicle) {
Super.oncreate (Icicle);
Setcontentview (r.layout.async_task_demo_activity);
Mprogressbar = (ProgressBar) Findviewbyid (r.id.async_task_progress);
Mimageview = (ImageView) Findviewbyid (R.id.async_task_displayer);
Final Imageloader loader = new Imageloader ();
Mgetimage = (Button) Findviewbyid (r.id.async_task_get_image);
Mgetimage.setonclicklistener (New View.onclicklistener () {
public void OnClick (View v) {
Loader.execute (IMAGEURL);
}
});
Mabort = (Button) Findviewbyid (R.id.asyc_task_abort);
Mabort.setonclicklistener (New View.onclicklistener () {
public void OnClick (View v) {
Loader.cancel (TRUE);
}
});
Mabort.setenabled (FALSE);
}

Private class Imageloader extends Asynctask<string, Integer, bitmap> {
private static final String TAG = "Imageloader";
@Override
protected void OnPreExecute () {
Initialize Progress and image
Mgetimage.setenabled (FALSE);
Mabort.setenabled (TRUE);
Mprogressbar.setvisibility (view.visible);
Mprogressbar.setprogress (0);
Mimageview.setimageresource (R.drawable.icon);
}

@Override
Protected Bitmap doinbackground (String ... url) {
/*
* ridiculous thing happened here, to the any Internet connections, either via HttpURLConnection
* or httpclient, you must declare the INTERNET permission in Androidmanifest.xml. Otherwise you'll get
* "unknownhostexception" when connecting or other tcp/ip/http exceptions rather than "SecurityException"
* which tells you need to declare INTERNET permission.
*/
try {
URL u;
HttpURLConnection conn = null;
InputStream in = null;
OutputStream out = null;
Final String filename = "Local_temp_image";
try {
u = new URL (url[0]);
conn = (httpurlconnection) u.openconnection ();
Conn.setdoinput (TRUE);
Conn.setdooutput (FALSE);
Conn.setconnecttimeout (20 * 1000);
in = Conn.getinputstream ();
out = openfileoutput (filename, context.mode_private);
byte[] buf = new byte[8196];
int seg = 0;
Final long total = Conn.getcontentlength ();
Long current = 0;
/*
* Without checking iscancelled (), the loop continues until reading-whole image done, i.e. the progress
* continues go up to 100. But OnPostExecute () won't be called.
* by checking iscancelled (), we can stop immediately, i.e. progress stops immediately if Cancel () is called.
*/
while (!iscancelled () && (seg = In.read (BUF))!=-1) {
Out.write (buf, 0, SEG);
Current + = SEG;
int progress = (int) ((float) current/(float) total * 100f);
Publishprogress (progress);
Systemclock.sleep (1000);
}
finally {
IF (conn!= null) {
Conn.disconnect ();
}
if (in!= null) {
In.close ();
}
if (out!= null) {
Out.close ();
}
}
Return Bitmapfactory.decodefile (Getfilestreampath (filename). GetAbsolutePath ());
catch (Malformedurlexception e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}
return null;
}

@Override
protected void Onprogressupdate (Integer ... progress) {
Mprogressbar.setprogress (Progress[0]);
}

@Override
protected void OnPostExecute (Bitmap image) {
if (image!= null) {
Mimageview.setimagebitmap (image);
}
Mprogressbar.setprogress (100);
Mprogressbar.setvisibility (View.gone);
Mabort.setenabled (FALSE);
}
}
}

Run results

The order is before downloading, downloading and downloading
Summarize
On how to use look at the document and this example is enough, next, use the attention:
1. The Asynctask object cannot be reused, that is, a Asynctask object can only execute () once, otherwise there will be an exception thrown "Java.lang.IllegalStateException:Cannot Execute task: The task is already running "

2. In Doinbackground () to check the return value of iscancelled (), if your asynchronous task can be canceled.
Cancel () simply sets an identity bit for the Asynctask object, and when cancel () is invoked, the only thing that happens is that the identity bit of the Asynctask object has changed, and after Doinbackground () execution is complete, onpostexecute () Will not be recalled, and Doinbackground () and onprogressupdate () will continue to execute until Doinbackground () ends. So the return value of iscancellled () is constantly checked in Doinbackground (), and it stops executing when it returns true, especially when there is a loop. As the above example, if the reading of the data iscancelled () Check out, the picture will still be downloaded, progress will always go, but the final picture will not be put on the UI (because OnPostExecute () is not recalled)!

The reason here is well understood, think of Java SE thread, there is no way to directly cacncel it off, those thread cancellation is simply to the thread to set the identity bit, and then in the run () method constantly check the identity.

3. If you want to use the network in your application, be sure not to forget to declare Internet permissions in the Androidmanifest, or you will report strange exception information, such as the above example, if you remove Internet permissions, you will throw " Unknownhostexception ". At first very puzzled, because the simulator can be normal Internet, and then Google found that the original is not permission, but the question is still not eliminated, since there is no declaration of network permissions, why not directly prompted without network permissions?

Compare the thread of Java SE
Thread is a very primitive class, it only has a run () method that, once started, cannot be stopped, it is only suitable for a very independent asynchronous task, that is, does not need to interact with the main thread, for other cases, such as the need to cancel or interact with the main thread, you need to add additional code to implement, and also pay attention to the problem of synchronization.
The asynctask is encapsulated and can be used directly, if you only perform a stand-alone asynchronous task, you can only implement Doinbackground ().
So, when there is a very independent task, you can consider using thread, other times, as much as possible with Asynctask.
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.