android AsyncTask 可以更新界面的后台任务

先看使用这个类

    在主线程中执行下面这两个步骤即可

    diTask = new DownloadImageTask(this);
    diTask.execute(url);

    DownloadImageTask是AsyncTask的子类。

    execute(url)函数的参数类型是AsyncTask模板类第一个参数类型。


需要自己继承AsyncTask模板类,并实现它的四个方法。

AsyncTask<String, Integer, Bitmap>

    第一个类型为doInBackground函数的参数类型

    第二个参数为onProgressUpdate函数的参数的类型,跟新界面用的

    第三个为doInBackground返回和onPostExecute传入的参数类型

public class DownloadImageTask extends AsyncTask<String, Integer, Bitmap> {

    private Context mContext;

    DownloadImageTask(Context context) {
        mContext = context;
    }


    //在背景线程运行之前执行,用于初始化,比如创建一个进度条之类的。

    protected void onPreExecute() {
        // We could do some setup work here before doInBackground() runs
    }

   

    //运行在背景线程中,执行耗时任务,不能更新ui

    protected Bitmap doInBackground(String... urls) {
        Log.v("doInBackground", "doing download of image");
        return downloadImage(urls);
    }


    //根据publishProgress的报告更新ui

    protected void onProgressUpdate(Integer... progress) {
        TextView mText = (TextView) ((Activity) mContext).findViewById(R.id.text);
        mText.setText("Progress so far: " + progress[0]);
    }


    //背景线程运行 完毕后执行,可以更新ui

    protected void onPostExecute(Bitmap result) {
        if(result != null) {
            ImageView mImage = (ImageView) ((Activity) mContext).findViewById(R.id.image);
            mImage.setImageBitmap(result);
        }
        else {
            TextView errorMsg = (TextView) ((Activity) mContext).findViewById(R.id.errorMsg);
            errorMsg.setText("Problem downloading image. Please try again later.");
        }
    }

    private Bitmap downloadImage(String... urls)
    {
      HttpClient httpClient = CustomHttpClient.getHttpClient();
      try {
        HttpGet request = new HttpGet(urls[0]);
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(params, 60000);   // 1 minute
        request.setParams(params);

        publishProgress(25);

        HttpResponse response = httpClient.execute(request);

        publishProgress(50);

        byte[] image = EntityUtils.toByteArray(response.getEntity());

        publishProgress(75);

        Bitmap mBitmap = BitmapFactory.decodeByteArray(image, 0, image.length);

        publishProgress(100);

        return mBitmap;
      } catch (IOException e) {
        // covers:
        //      ClientProtocolException
        //      ConnectTimeoutException
        //      ConnectionPoolTimeoutException
        //      SocketTimeoutException
        e.printStackTrace();
      }
      return null;
    }

}



参考文章:http://www.cnblogs.com/xingmeng/archive/2012/05/24/2516481.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值