对Android中的AsyncTask进行函数化的封装,简洁调用

转载 2012年03月21日 13:17:38

为了使UI在数据获取时不僵死,数据获取需要在新开Worker线程中进行,然后将返回结果在UI线程中进行读取并渲染页面。面对这种异步处理,到底如何写才简洁,先后面临过三种实现方式。

首先是最原始的Java方式,new 一个Thread出来,将处理Runnable进去执行,执行完之后通过handler post到ui线程去更新界面。然后发现1.5后有了AsyncTask,非常好用,以后的项目中全部改成衍生出一个AsyncTask的子类,类中自然定义了运行前方法、运行中方法和运行后在ui中运行的方法。目前我做的项目中对AsyncTask做了封装,把它从原本的子类编写的过程,改成了函数调用方式,这就是目前正使用的第三种方法。

clip_image001

一个Android应用中,Activity通常可以建立以上层次关系。然后,在BaseActivity中对AsyncTask进行了封装,形成doAsync方法。方法体内创建一个新的AsyncTask并执行,由于AsyncTask是泛型参数,doAsync方法中传入的接口的参数也对应使用了泛型。至此,一个典型的异步调用的案例如下:

this.doAsync(new Callable() {

// 希望异步加载的数据

public String call() throws Exception {

String resu = NetworkTool.httpGetURL(

"http://www.baidu.com", "GBK");

return resu;

}

}, new Callback() {

// 当加载完成后回调,在UI线程中的操作

public void onCallback(final String resu) {

if (null != resu) {

tv_text1.setText(getRT().text1 + resu);

} else {

Tools.ShowNetErr(HomeActivity.this);

}

}

});

这样,就从本来继承AsyncTask创建一个子类,然后初始化,然后运行的开发过程转变为了函数调用的过程。可以看到,调用可是简洁了很多!

为了实现它,我们附上BaseActivity中如下封装代码,需要说明的是这不是我的原创,我借鉴于Andengine引擎的实现代码进行的修改。

附源码:

public class ActivityUtils {

public static void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback) {

ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, null, false);

}

public static void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable pCallable, final Callback pCallback) {

ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, false);

}

public static void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback, final boolean pCancelable) {

ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, null, pCancelable);

}

public static void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable pCallable, final Callback pCallback, final boolean pCancelable) {

ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, pCancelable);

}

public static void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback) {

ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, pExceptionCallback, false);

}

public static void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback) {

ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, pExceptionCallback, false);

}

public static void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback, final boolean pCancelable) {

ActivityUtils.doAsync(pContext, pContext.getString(pTitleResID), pContext.getString(pMessageResID), pCallable, pCallback, pExceptionCallback, pCancelable);

}

public static void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback, final boolean pCancelable) {

new AsyncTask() {

private ProgressDialog mPD;

private Exception mException = null;

@Override

public void onPreExecute() {

this.mPD = ProgressDialog.show(pContext, pTitle, pMessage, true, pCancelable);

if(pCancelable) {

this.mPD.setOnCancelListener(new OnCancelListener() {

@Override

public void onCancel(final DialogInterface pDialogInterface) {

pExceptionCallback.onCallback(new CancelledException());

pDialogInterface.dismiss();

}

});

}

super.onPreExecute();

}

@Override

public T doInBackground(final Void... params) {

try {

return pCallable.call();

} catch (final Exception e) {

this.mException = e;

}

return null;

}

@Override

public void onPostExecute(final T result) {

try {

this.mPD.dismiss();

} catch (final Exception e) {

Log.e("Error", e.toString());

}

if(this.isCancelled()) {

this.mException = new CancelledException();

}

if(this.mException == null) {

pCallback.onCallback(result);

} else {

if(pExceptionCallback == null) {

if (this.mException != null)

Log.e("Error", this.mException.toString());

} else {

pExceptionCallback.onCallback(this.mException);

}

}

super.onPostExecute(result);

}

}.execute((Void[]) null);

}

public static void doProgressAsync(final Context pContext, final int pTitleResID, final ProgressCallablepCallable, final Callback pCallback) {

ActivityUtils.doProgressAsync(pContext, pTitleResID, pCallable, pCallback, null);

}

public static void doProgressAsync(final Context pContext, final int pTitleResID, final ProgressCallablepCallable, final Callback pCallback, final Callback pExceptionCallback) {

new AsyncTask() {

private ProgressDialog mPD;

private Exception mException = null;

@Override

public void onPreExecute() {

this.mPD = new ProgressDialog(pContext);

this.mPD.setTitle(pTitleResID);

this.mPD.setIcon(android.R.drawable.ic_menu_save);

this.mPD.setIndeterminate(false);

this.mPD.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

this.mPD.show();

super.onPreExecute();

}

@Override

public T doInBackground(final Void... params) {

try {

return pCallable.call(new IProgressListener() {

@Override

public void onProgressChanged(final int pProgress) {

onProgressUpdate(pProgress);

}

});

} catch (final Exception e) {

this.mException = e;

}

return null;

}

@Override

public void onProgressUpdate(final Integer... values) {

this.mPD.setProgress(values[0]);

}

@Override

public void onPostExecute(final T result) {

try {

this.mPD.dismiss();

} catch (final Exception e) {

Log.e("Error", e.getLocalizedMessage());

/* Nothing. */

}

if(this.isCancelled()) {

this.mException = new CancelledException();

}

if(this.mException == null) {

pCallback.onCallback(result);

} else {

if(pExceptionCallback == null) {

Log.e("Error", this.mException.getLocalizedMessage());

} else {

pExceptionCallback.onCallback(this.mException);

}

}

super.onPostExecute(result);

}

}.execute((Void[]) null);

}

public static void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final AsyncCallable pAsyncCallable, final Callback pCallback, final Callback pExceptionCallback) {

final ProgressDialog pd = ProgressDialog.show(pContext, pContext.getString(pTitleResID), pContext.getString(pMessageResID));

pAsyncCallable.call(new Callback() {

@Override

public void onCallback(final T result) {

try {

pd.dismiss();

} catch (final Exception e) {

Log.e("Error", e.getLocalizedMessage());

/* Nothing. */

}

pCallback.onCallback(result);

}

}, pExceptionCallback);

}

public static class CancelledException extends Exception {

private static final long serialVersionUID = -78123211381435595L;

}

}

public interface AsyncCallable {

// ===========================================================

// Final Fields

// ===========================================================

// ===========================================================

// Methods

// ===========================================================

/**

* Computes a result asynchronously, return values and exceptions are to be handled through the callbacks.

* This method is expected to return almost immediately, after starting a {@link Thread} or similar.

*

* @return computed result

* @throws Exception if unable to compute a result

*/

public void call(final Callback pCallback, final Callback pExceptionCallback);

}

public interface Callback {

// ===========================================================

// Final Fields

// ===========================================================

// ===========================================================

// Methods

// ===========================================================

/**

* 当加载完成后回调,加载完毕的事后处理

*/

public void onCallback(final T pCallbackValue);

}

public interface IProgressListener {

// ===========================================================

// Constants

// ===========================================================

// ===========================================================

// Methods

// ===========================================================

/**

* @param pProgress between 0 and 100.

*/

public void onProgressChanged(final int pProgress);

}

public interface IProgressListener {

// ===========================================================

// Constants

// ===========================================================

// ===========================================================

// Methods

// ===========================================================

/**

* @param pProgress between 0 and 100.

*/

public void onProgressChanged(final int pProgress);

}

public class BaseActivity extends Activity {

/**

*

* @param 模板参数,操作时要返回的内容

* @param pCallable 需要异步调用的操作

* @param pCallback 回调

*/

protected void doAsync(final Callable pCallable, final Callback pCallback) {

ActivityUtils.doAsync(this, null, "内容读取中,请稍等...", pCallable, pCallback, null, false);

}

protected void doAsync(final CharSequence pTitle, final CharSequence pMessage, final CallablepCallable, final Callback pCallback) {

ActivityUtils.doAsync(this, pTitle, pMessage, pCallable, pCallback, null, false);

}

/**

* Performs a task in the background, showing a {@link ProgressDialog},

* while the {@link Callable} is being processed.

*

* @param

* @param pTitleResID

* @param pMessageResID

* @param pErrorMessageResID

* @param pCallable

* @param pCallback

*/

protected void doAsync(final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback) {

this.doAsync(pTitleResID, pMessageResID, pCallable, pCallback, null);

}

/**

* Performs a task in the background, showing a indeterminate {@link ProgressDialog},

* while the {@link Callable} is being processed.

*

* @param

* @param pTitleResID

* @param pMessageResID

* @param pErrorMessageResID

* @param pCallable

* @param pCallback

* @param pExceptionCallback

*/

protected void doAsync(final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback) {

ActivityUtils.doAsync(this, pTitleResID, pMessageResID, pCallable, pCallback, pExceptionCallback);

}

/**

* Performs a task in the background, showing a {@link ProgressDialog} with an ProgressBar,

* while the {@link AsyncCallable} is being processed.

*

* @param

* @param pTitleResID

* @param pMessageResID

* @param pErrorMessageResID

* @param pAsyncCallable

* @param pCallback

*/

protected void doProgressAsync(final int pTitleResID, final ProgressCallable pCallable, final CallbackpCallback) {

this.doProgressAsync(pTitleResID, pCallable, pCallback, null);

}

/**

* Performs a task in the background, showing a {@link ProgressDialog} with a ProgressBar,

* while the {@link AsyncCallable} is being processed.

*

* @param

* @param pTitleResID

* @param pMessageResID

* @param pErrorMessageResID

* @param pAsyncCallable

* @param pCallback

* @param pExceptionCallback

*/

protected void doProgressAsync(final int pTitleResID, final ProgressCallable pCallable, final CallbackpCallback, final Callback pExceptionCallback) {

ActivityUtils.doProgressAsync(this, pTitleResID, pCallable, pCallback, pExceptionCallback);

}

/**

* Performs a task in the background, showing an indeterminate {@link ProgressDialog},

* while the {@link AsyncCallable} is being processed.

*

* @param

* @param pTitleResID

* @param pMessageResID

* @param pErrorMessageResID

* @param pAsyncCallable

* @param pCallback

* @param pExceptionCallback

*/

protected void doAsync(final int pTitleResID, final int pMessageResID, final AsyncCallable pAsyncCallable, final Callback pCallback, final Callback pExceptionCallback) {

ActivityUtils.doAsync(this, pTitleResID, pMessageResID, pAsyncCallable, pCallback, pExceptionCallback);

}

}

Android中AsyncTask的函数调用顺序

转自:http://blog.csdn.net/liuhe688/article/details/6532519
  • xunfan
  • xunfan
  • 2014年10月22日 16:23
  • 1397

Android中AsyncTask进行后台下载文件并在下拉菜单显示下载进度

在开发过程中,总会需要从网络上下载文件,有时候还需要将下载进度显示在下拉菜单中。 现在写了一个Demo,封装了AsyncTask下载文件和进度显示的代码,以后在做项目的时候能够直接进行使用。 ...
  • bfboys
  • bfboys
  • 2016年11月30日 22:05
  • 146

Android中使用Handler和AsyncTask进行异步操作

1.Handler Handler相关说明: 主要接受子线程发送的数据, 并用此数据配合主线程更新UI。 解释:安卓的UI线程(即OnCreate函数创建的线程)是线程非安全的。...
  • he90227
  • he90227
  • 2014年07月28日 14:09
  • 1108

android 用AsyncTask进行异步开发

AsyncTask和Handler对比 1 ) AsyncTask实现的原理,和适用的优缺点 AsyncTask,是android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异...
  • zztfj
  • zztfj
  • 2013年05月29日 08:38
  • 515

使用AsyncTask--->对Handler 和Thread 进行了封装

AsyncTask的实现原理,也是基于异步消息处理机制的. (1)AsyncTask是一个抽象类, 我们在使用的时候, 必须创建一个子类来继承它.  在继承的时候,我们可以为AsyncTask指定...
  • aydehua
  • aydehua
  • 2014年11月21日 00:19
  • 278

对AsyncTask进行封装,简化繁琐的异步操作

对于android的异步操作,往往有二种方法给予我们选择。      一:Thread+Handler      二:  AsyncTask        对于二者的相同与异同...
  • jdsjlzx
  • jdsjlzx
  • 2012年05月27日 15:14
  • 3606

对AsyncTask进行封装,简化繁琐的异步操作

 对于android的异步操作,往往有二种方法给予我们选择。      一:Thread+Handler      二:  AsyncTask        ...

Android 6.0 运行时权限简洁封装

参考资料如下: Android Runtime Permissions Android 6.0 运行时权限处理完全解析 MeloDev的Android 6.0 运行时权限简洁封装 MeloDev的...

让Activity更加简洁第二篇---AsyncTask的使用姿势

如果你点开的这篇文章,那么 AsyncTask 的基本用法肯定是掌握了的。这篇文章不是分析 AsyncTask的内部原理,而是侧重于如何使用,让我们视图层中的Activity看起来更舒适。本文的项目地...

[Android]仿微信开关按钮:)扁平化简洁风

自定义开关,仿微信。
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:对Android中的AsyncTask进行函数化的封装,简洁调用
举报原因:
原因补充:

(最多只允许输入30个字)