Android Asynchronous Task (2)

Source: Internet
Author: User

1. Load a picture on the network using an asynchronous task

We can open this URL: http://img1.3lian.com/img2011/07/20/05.jpg can see a very good picture, we will show this picture, first, or first to layout, we want to display a picture, So we need a imageview layout, the layout is very simple, a imageview can be:

  

1 <?xml version= "1.0" encoding= "Utf-8"?>
2 <linearlayout
3 xmlns:android= "http://schemas.android.com/apk/res/android"
4 android:layout_width= "Match_parent"
5 android:layout_height= "Match_parent" >
6
7
8 android:scaletype= "Fitxy"
9
Ten android:layout_height= "Match_parent"/>
</LinearLayout>

Then we're going to write an activity to show this image, but to load the image on the network, we need to get the picture from a stream of URLs, so we're going to write a way to get this picture:

  


2 try {
3 return Drawable.createfromstream ((InputStream) (new URL (URL)). OpenStream (), "test");
4 }
5 catch (IOException e) {
6 e.printstacktrace ();
7 }
8 return null;
9 }

Open the stream from the URL, cast it to InputStream, and get the drawable from the stream.

Now that we can get the picture, we have to consider a problem, if the picture is very large, loading very slowly what to do, we do not have to wait a long time? It doesn't matter, then we can use the asynchronous task.

First we're going to write an inner class that inherits from the asynchronous task and needs to overload the Dobackground method:

  

1  Private class Imageasyntask extends Asynctask<void, Void, drawable> {

3 @Override
4 protected drawable doinbackground (Void ... params) {
5 String url = "Http://img1.3lian.com/img2011/07/20/05.jpg";
6 return loadimages (URL);
7 }
8
9 @Override
Ten protected void OnPostExecute (drawable result) {
One super.onpostexecute (result);
Mdialog.dismiss ();
mimage.setimagedrawable (Result);
+ }
15
@Override
protected void OnPreExecute () {
Super.onpreexecute ();
mdialog.show ();
( }
+ }

First look at this method: OnPreExecute () This method is executed in front of the doinbackground. We write this method, we need to wait for the picture before the time, write a progressdialog, display, prompting the user, is currently loading the picture, need to wait a while. Run Dobackground at the same time in the background operation.

The OnPostExecute (drawable result) method is executed after the Dobackground is completed, and it is known that the method must be completed after Dobackground To get the results drawable as a parameter to the OnPostExecute method inside, the implementation of this method means that it has been loaded, we need to progressdialog disappear, and then the picture can be displayed, the whole process is very simple.

Look at the code for the entire activity:

  

1 package com.test.asyntask;
2
3 Import java.io.IOException;
4 Import Java.io.InputStream;
5 Import Java.net.URL;
6
7 Import android.app.Activity;
8 Import Android.app.ProgRessdialog;
9 Import android.graphics.drawable.Drawable;
Ten import Android.os.AsyncTask;
Import Android.os.Bundle;
ImportAndroid.widget.ImageView;
13
Import COM.TEST.R;
15
public class Asyntask extends Activity {
17
Private ImageView mimage;
Private ProgressDialog Mdialog;
20
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.asyn_task);
25
Mdialog = new ProgRessdialog (this);
Mdialog.settitle ("Please wait a moment");
Mdialog.setmessage ("Loading ...");
29
Mimage = (ImageView) Findviewbyid (r.id.img);
31New Imageasyntask (). Execute ();
32}
33
Private class Imageasyntask extends Asynctask<void, Void, drawable> {
35
@Override
PNS protected drawable doinbackground (Void ... params) {
The String url = "Http://img1.3lian.com/img2011/07/20/05.jpg";
loadimages return (URL);
40}
41
@Override
protected void OnPostExecute (drawable result) {
Super.onpostexecute (result);
Mdialog.dismiss ();
Mimage.setimagedrawable (result);
47}
48
@Override
protected void OnPreExecute () {
Wuyi Super.onpreexecute ();
Mdialog.show ();
53}
54}
55
@Override
protected void OnDestroy () {
Super.ondestroy ();
Mdialog.dismiss ();
60}
61
drawable public loadimages (String URL) {
try {
Return Drawable.createfromstream ((InputStream) (new URL (URL)). OpenStream (), "test");
65}
IOException (e) {
E.printstacktrace ();
68}
return null;
70}
+ +}

Run it and look at the effect:

1. When the ProgressDialog is displayed, the picture is loaded but the picture is not loaded:

  

It is also important to note that you need to add a link network to the manifest:

  

1 <uses-permission android:name= "Android.permission.INTERNET"/>

Also in Ondestory () to the time to progressdialog dismiss off, not to quit the application when the error.

2. Press the back key to pause the asynchronous task

When you use Asyntask asynchronous tasks to process time-consuming operations (work), you typically increase the ProgressDialog progress bar to show the wait action (or load progress).

The return key is pressed, because the focus is on ProgressDialog, ProgressDialog captures the return key operation, and the activity does not respond to the return key operation.

If you want to implement, when the time-consuming operation (ProgressDialog is being displayed), press the back key to end the current work operation.

You need to be aware of the ProgressDialog settings:

Progress_dialog.setcancelable (TRUE);//Response cancel operation, here if set false, press the return key ProgressDialog also does not disappear.
Progress_dialog.setoncancellistener (New Oncancellistener () {
@Override
public void OnCancel (Dialoginterface dialog) {
TODO auto-generated Method Stub

AsynTask.this.cancle (TRUE);//execute asynchronous thread cancel operation
}
});

Also note that Asyntask executes the cancele () operation, the corresponding method is how to execute.

You can stop a running task with cancel (true). A Cancel would let the task finish it doinbackground but would never call OnPostExecute. You could interrupt your background routine by checking isCanceled () and so return earlier since the task was killed.

Reference: http://stackoverflow.com/questions/8209035/ Android-stop-asynctask-when-back-button-is-pressed-and-return-to-previous-acti

Android Asynchronous Task (2)

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.