当前位置:操作系统 > 安卓/Android >>

Android实战技巧:多线程AsyncTask

Understanding AsyncTask
AsyncTask是Android 1.5 Cubake加入的用于实现异步操作的一个类,在此之前只能用Java SE库中的Thread来实现多线程异步,AsyncTask是Android平台自己的异步工具,融入了Android平台的特性,让异步操作更加的安全,方便和实用。实质上它也是对Java SE库中Thread的一个封装,加上了平台相关的特性,所以对于所有的多线程异步都强烈推荐使用AsyncTask,因为它考虑,也融入了Android平台的特性,更加的安全和高效。
AsyncTask可以方便的执行异步操作(doInBackground),又能方便的与主线程进行通信,它本身又有良好的封装性,可以进行取消操作(cancel())。关于AsyncTask的使用,文档说的很明白,下面直接上实例。

实例
这个实例用AsyncTask到网络上下载图片,同时显示进度,下载完图片更新UI。


[java]
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 be reused, i.e. if you have executed one AsyncTask, you must discard it, you cannot execute it again.
 * If you try to execute an executed AsyncTask, you will get "java.lang.IllegalStateException: Cannot execute task: the task is already running"
 * In this demo, if you click "get the image" button twice at any time, you will receive "IllegalStateException".
 * About cancellation:
 * You can call AsyncTask#cancel() at any time during AsyncTask executing, but the result is onPostExecute() is not called after
 * doInBackground() finishes, which means doInBackground() is not stopped. AsyncTask#isCancelled() returns true after cancel() getting
 * called, so if you want to really cancel the task, i.e. stop doInBackground(), you must check the return value of isCancelled() in
 * doInBackground, when there are loops in doInBackground in particular.
 * This is the same to Java threading, in which is no effective way to stop a running thread, only way to do 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 = "/2012/0515/20120515100913728.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) { 
        /*
         * 易做图ing ridiculous thing happened here, to use any Internet connections, either via HttpURLConnection
         * or HttpClient, you must declare INTERNET permission in AndroidManifest.xml. Otherwise you will 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); 
          

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,