您的位置:首页 > 其它

AsyncTask

2016-01-13 09:54 295 查看
AsyncTask也叫做“异步任务”,是一个抽象类

AsyncTask约定了在子线程中执行任务的抽象方法,开发者可以在自定义AsyncTask的实现类中重写该方法,

则AsyncTask在工作时会自动开启子线程执行相关代码

AsyncTask类的声明:

public abstract class AsyncTask<Param,Progress,Result>

Param 执行异步任务后,需要参数的数据类型

Progress 执行异步任务过程中,标识进度的数据类型

Result 执行异步任务后,需要返回的结果的数据类型

AsyncTask中的抽象方法: public abstract Result doInBackground(params... params)

让AsyncTask开始工作:

public final AsyncTask<params,Progress,Result> execute(params...params)

该方法被调用后,会自动开启子线程并调用dnInBackground()方法,该方法

必须在UI线程中调用

案例:

布局:

[html] view
plaincopyprint?

<Button

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:layout_marginTop="104dp"

android:onClick="doAsyncTask"

android:text="开始" />

MainActivity:

[java] view
plaincopyprint?

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

System.out.println("onCreate" + Thread.currentThread().getId());

}

public void doAsyncTask(View view){

new InnerAsyncTask().execute("");

}

private class InnerAsyncTask extends AsyncTask<Object, Object, Object>{

@Override

protected Object doInBackground(Object... params) {

for(int i = 0; i < 30;i++){

System.out.println("InnerAsyncTask" + Thread.currentThread().getId());

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

return null;

}

}

}

AsyncTask更新UI

AsyncTask约定了任务执行完毕后的回调方法,该方法并不是抽象的,开发者可以选择性的实现。

protected void onPostExecute(Result result)

该方法是运行在主线程的方法

实例:

布局:

[html] view
plaincopyprint?

<Button

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:layout_marginTop="104dp"

android:onClick="doAsyncTask"

android:text="开始" />

<ImageView

android:id="@+id/imageView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@+id/button1"

android:layout_centerHorizontal="true"

android:layout_marginTop="22dp"

android:src="@drawable/abs" />

MainActivity:

[java] view
plaincopyprint?

public class MainActivity extends Activity {

private ImageView image;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

image = (ImageView) findViewById(R.id.imageView1);

// System.out.println("onCreate" + Thread.currentThread().getId());

}

public void doAsyncTask(View view){

new InnerAsyncTask().execute("");

}

private class InnerAsyncTask extends AsyncTask<String,Integer, Bitmap>{

@Override

protected Bitmap doInBackground(String... params) {

try {

Thread.sleep(3000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return BitmapFactory.decodeResource(getResources(), R.drawable.abc);

}

@Override

protected void onPostExecute(Bitmap result) {

image.setImageBitmap(result);

}

}

}

AsyncTask更新进度

AsyncTask约定了任务执行过程中,更新进度的回调方法,该方法并不是抽象的,开发者可以选择性地实现。

protected void onProgressUpdate(Progress... values)(该方法运行在主线程)

在任务执行过程中,可以调用publishProgress()方法提交进度,使得onProgressUpdate()方法被回调

实例

布局:

[html] view
plaincopyprint?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent" >

<TextView

android:id="@+id/tv_pb"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="100%"

android:visibility="gone"

android:textSize="16sp"/>

<Button

android:id="@+id/btn_update"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:layout_marginTop="104dp"

android:onClick="doAsyncTask"

android:text="开始" />

<ImageView

android:id="@+id/iv_image"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@+id/btn_update"

android:layout_centerHorizontal="true"

android:layout_marginTop="22dp"

android:src="@drawable/abs" />

<ProgressBar

android:id="@+id/pb_progress"

style="?android:attr/progressBarStyleHorizontal"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_alignParentTop="true"

android:max="100"

android:visibility="gone"

android:layout_alignRight="@+id/btn_update"

android:layout_marginTop="32dp" />

</RelativeLayout>

LoadImage:

[java] view
plaincopyprint?

public class LoadImage extends AsyncTask<String, Integer, Object> {

private Context context;

private ImageView imageview;

private Bitmap image;

private Button button;

private ProgressBar pg;

private TextView tv;

public LoadImage(Context context, Button button, ImageView imageview,

ProgressBar pg, TextView tv) {

this.context = context;

this.imageview = imageview;

this.button = button;

this.pg = pg;

this.tv = tv;

}

@Override

protected Object doInBackground(String... params) {

for (int i = 0; i <= 100; i++) {

publishProgress(i);

try {

Thread.sleep(50);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

image = BitmapFactory.decodeResource(context.getResources(),

R.drawable.abc);

return null;

}

@Override

protected void onProgressUpdate(Integer... values) {

// TODO Auto-generated method stub

pg.setProgress(values[0]);

tv.setText(values[0] + "%");

}

@Override

protected void onPostExecute(Object result) {

imageview.setImageBitmap(image);

button.setEnabled(true);

pg.setVisibility(View.GONE);

tv.setVisibility(View.GONE);

}

}

MainActivity:

[java] view
plaincopyprint?

public class MainActivity extends Activity {

private ImageView image;

private Button button;

private ProgressBar pg;

private TextView tv;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

image = (ImageView) findViewById(R.id.iv_image);

button = (Button) findViewById(R.id.btn_update);

pg = (ProgressBar) findViewById(R.id.pb_progress);

tv = (TextView) findViewById(R.id.tv_pb);

}

public void doAsyncTask(View view){

button.setEnabled(false);

pg.setVisibility(View.VISIBLE);

tv.setVisibility(View.VISIBLE);

new LoadImage(this,button,image,pg,tv).execute("");

}

}

AsyncTask是一个综合了任务的执行、进度更新、结果提交的类,使用AsyncTask

可以集中的编写某个异步任务的全部代码,而不必关心线程间的通信问题,降低了

编码出错几率,并有效的提高了代码的可阅读性、可维护性等。

小案例之异步加载图片

使用到的技术: Canvas(画布)、Paint(画笔)

Canvas(画布):用来决定画布的基础属性,执行绘制

Paint(画笔):设置颜色、设置字体、其他的设置

同一次绘图过程中,可能需要多个画笔对象,或多次调整画笔的属性

使用Canvas:

public Canvas()

public Canvas(Bitmap bitmap)

public void drawRect(float left,float top,float right,float bottom,Paint paint)

public void drawBitmap(Bitmap bitmap,float left,float top,Paint paint)

public void drawText(String text,float x,float y,Paint paint)

使用Paint:

public Paint()

public native void setColr(int color)

public native void setAntiAlias(boolean aa)

public native void setTextSize(float textSize)

public void setTextAlign(Align align)

public Xfermode setXfermode(Xfermode xfermode)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: