Android AsyncTask详解

一、AsyncTask基本结构介绍

首先,顾名思义,AsyncTask是异步任务。

为什么要异步任务?

因为只有UI线程,即主线程可以对控件进行更新操作。好处是保证UI稳定性,避免多线程对UI同时操作。

同时要把耗时任务放在非主线程中执行,否则会造成阻塞,抛出无响应异常。

AsyncTask是安卓封装好的异步机制。(当然也可以自己写new thread,handler)

AsyncTask是抽象类,要被继承后使用,形如

Params是启动任务时输入参数的类型,Progress是后台任务执行中返回进度值的类型,Result是后台任务执行完成后返回结果的类型。在下面的代码中会有介绍。
子类的方法:

doInBackgroud,继承后需要必须重写的方法,异步执行将要完成的任务。只有该方法是在子线程中执行,不能更新UI;下面的3个方法都是在主线程中执行,可以更新UI。

onPreExecute,执行操作前被调用,用于初始化。

onPostExecute,任务执行完后自动调用的方法,并将doInbackgroud的结果值传入该方法,即可以进行一些更新UI的操作。

onProgressUpdate,在doInBackgroud方法中调用publishProgress时被执行,可以更新任务的执行进度。

使用方法:

在UI线程中创建继承自Asynctask类的自定义的,

注意事项:

必须在UI线程中创建Asynctask示例,调用其execute方法。

重写的4个方法是系统自动调用的,不能手动调用。

二、使用AsyncTask加载网络图片以及使用AsyncTask模拟进度条

在进入页有两个按钮,分别对应如题所述两个功能。

这里写代码片
activity_main.xml:




[plain] view plaincopy
01.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
02.    android:layout_width="fill_parent"  
03.    android:layout_height="fill_parent"  
04.    android:orientation="vertical" >  
05.  
06.    <Button  
07.        android:id="@+id/button1"  
08.        android:layout_width="match_parent"  
09.        android:layout_height="wrap_content"  
10.        android:text="异步加载网络图片" />  
11.  
12.    <Button  
13.        android:id="@+id/button2"  
14.        android:layout_width="match_parent"  
15.        android:layout_height="wrap_content"  
16.        android:text="模拟进度条" />  
17.  
18.</LinearLayout> 

首先在自定义的xml中加入imageview和progressbar,progressbar的可见性为gone,即初始不可见。

activity_image.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/image"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="146dp"
    />


    <ProgressBar
        android:id="@+id/progressBar1"
        android:visibility="gone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="48dp" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="43dp"
        android:text="加载图片:"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

activity_progressbar.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:padding="16dp">

    <ProgressBar
        android:id="@+id/progressBar2"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="209dp" />

</RelativeLayout>

MainActivity类:

package com.example.asynctaskdemo;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO 自动生成的方法存根
                Intent intent = new Intent(MainActivity.this,
                        LoadImageActivity.class);
                MainActivity.this.finish();
                startActivity(intent);
            }
        });

        Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO 自动生成的方法存根
                Intent intent = new Intent(MainActivity.this,
                        ProgressBarActivity.class);
                MainActivity.this.finish();
                startActivity(intent);
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

界面到这里就结束了。下面说说重头戏。

LoadImageActivity.java:

package com.example.asynctaskdemo;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URLConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class LoadImageActivity extends Activity {

    private ProgressBar progressBar;
    private ImageView imageView;
    private String URL = "http://avatar.csdn.net/F/1/0/3_u012422829.jpg";


    //解释下这个类的三个参数: String是input的,是地址;Bitmap是结果;Progress不需要中途返回信息,所以是Void
    class LoadImageAsyncTask extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected void onPreExecute() {
            // TODO 自动生成的方法存根
            progressBar.setVisibility(View.VISIBLE);
            super.onPreExecute();
        }

        // 开启异步线程执行操作
        @Override
        protected Bitmap doInBackground(String... params) {
            // TODO 自动生成的方法存根
            String url = params[0];
            Bitmap bitmap = null;
            InputStream is = null;
            try {
                // 先睡3s,不然速度太快,看不出效果
                Thread.sleep(3000);
                URLConnection urlConnection = new java.net.URL(url)
                        .openConnection();
                is = urlConnection.getInputStream();
                BufferedInputStream bfis = new BufferedInputStream(is);
                bitmap = BitmapFactory.decodeStream(bfis);
                is.close();
                bfis.close();
            } catch (MalformedURLException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }

            return bitmap; //return给onPostExecute方法
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            // TODO 自动生成的方法存根
            progressBar.setVisibility(View.GONE);
            imageView.setImageBitmap(result);
            super.onPostExecute(result);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image);
        progressBar = (ProgressBar) findViewById(R.id.progressBar1);
        imageView = (ImageView) findViewById(R.id.imageView1);

        //在主线程中不能直接调用那个类中重写的方法,只能调用execute,系统会自动去执行pre,再执行doInBackground,执行完毕后再执行post
        new LoadImageAsyncTask().execute(URL);  //参数传递给doInBackground方法
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

我们在这个类中定义了一个内部类LoadImageAsyncTask,继承自AsyncTask,它的三个参数在注释中有解释。然后在界面启动时new一个对象,调用其execute方法。这里要特别注意,我们不能调用重写的4个方法,那是系统自动调用的。调用execute之后,系统先调用onpreexecute做初始化操作,再调用doinbackground, doinbackground执行完毕后返回的参数传递给onpostexecute,一般用那个方法做一些更新UI的操作。这里没有用到onProgressUpdate,OK,我们下面的例子有。

另外一个,ProgressBarActivity.java:

package com.example.asynctaskdemo;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class ProgressBarActivity extends Activity {

    private ProgressBar progressBar;
    private ProgressAsyncTask progressAsyncTask;

    class ProgressAsyncTask extends AsyncTask<Void, Integer, Void> {

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO 自动生成的方法存根
            for (int i = 0; i < 100; i++) {
                publishProgress(i);// i值传递给onprogressupdate
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }

            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            // TODO 自动生成的方法存根
            super.onProgressUpdate(values);
            progressBar.setProgress(values[0]);  //更新进度
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO 自动生成的方法存根
            progressBar.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), "完成任务", Toast.LENGTH_SHORT).show();
            super.onPostExecute(result);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progressbar);
        progressBar = (ProgressBar) findViewById(R.id.progressBar2);
        progressAsyncTask = new ProgressAsyncTask();
        progressAsyncTask.execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

附上源代码下载地址:http://yunpan.cn/cQJxawcIvc368 访问密码 6e44

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值