android异步任务工具类,模拟android的AsyncTask类——异步任务工具类

Android的AsyncTask类是处理异步任务的工具类,使程序员不用new Thread,不用写handler,只要使用AsyncTask类就能实现异步任务的处理了,但是不能说只用AsyncTask类而不要handler了,因为AsyncTask类在源码实现时,起的是一个线程池,在这个线程池中会有一定数量的线程。

AsyncTask类部分源码:

/**

* An {@link Executor} that can be used to execute tasks in parallel.

*/

public static final Executor THREAD_POOL_EXECUTOR

= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,

TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

所以,在使用AsyncTask类时,不能盲目。。

参看AsyncTask类的源码,下面是模拟AsyncTask类功能的代码,就是把new Thread() 和 handler封装在一起。。。

package com.wang.mobilesafe.utils;

import android.os.Handler;

/**

* 模拟android的AsyncTask类

*

* 一个异步任务的工具类

*

* 模板设计模式

* @author HeJW

*

*/

public abstract class MyAsyncTask {

private Handler handler = new Handler(){

public void handleMessage(android.os.Message msg) {

onPostExecute();

};

};

/**

* 耗时任务开始之前执行的方法

*/

public abstract void onPreExecute();

/**

* 耗时任务执行之后调用的方法

*/

public abstract void onPostExecute();

/**

* 执行的耗时任务,运行在子线程中

*/

public abstract void doInBackground();

/**

* 执行任务

*/

public void execute(){

onPreExecute();

new Thread(){

public void run() {

doInBackground();

handler.sendEmptyMessage(0);

};

}.start();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值