项目中使用到的封装---后台子线程执行任务,前台显示加载条

此封装后为一个抽象类LoadingDialog<Input, Result>,使用方法为:

1.写一个类继承该抽象类.(可以使用与LoadingDialog相同的传入参数)

2.重写doInBackground实现加载对话框弹出后,后台完成的具体业务逻辑(此方法运行在子线程).如果想增加进度条,可以改写LoadingDialogonProgressUpdate()来实现.

3.重写doStuffWithResult来操作doInBackground中获得的结果.(此方法运行在UI线程)

 
 

代码如下:

package uk.ac.essex.musicplayer.dialog;

import uk.ac.essex.musicplayer.api.WSError;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.widget.Toast;

public abstract class LoadingDialog<Input, Result> extends AsyncTask<Input, WSError, Result> {

	private ProgressDialog mProgressDialog;
	/**
	 * 相当于传入Context
	 */
	protected Activity mActivity;
	/**
	 * 加载时的提示信息
	 */
	private int mLoadingMsg;
	/**
	 * 加载失败的提示信息
	 */
	private int mFailMsg;

	public LoadingDialog(Activity activity, int loadingMsg, int failMsg) {
		this.mActivity = activity;
		this.mLoadingMsg = loadingMsg;
		this.mFailMsg = failMsg;
	}

	@Override
	public void onCancelled() {
		failMsg();
		super.onCancelled();
	}

	@Override
	public void onPreExecute() {
		String title = "";
		String message = mActivity.getString(mLoadingMsg);
		mProgressDialog = ProgressDialog.show(mActivity, title, message, true, true, new OnCancelListener() {

			public void onCancel(DialogInterface dialogInterface) {
				LoadingDialog.this.cancel(true);
			}

		});
		super.onPreExecute();
	}

	/**
	 * 子类重写该方法来实现对话框弹出时,后台执行的具体的业务逻辑
	 */
	@Override
	public abstract Result doInBackground(Input... params);

	@Override
	public void onPostExecute(Result result) {
		super.onPostExecute(result);

		mProgressDialog.dismiss();

		if (result != null) {
			doStuffWithResult(result);
		} else {
			failMsg();
		}
	}

	protected void failMsg() {
		Toast.makeText(mActivity, mFailMsg, 2000).show();
	}

	/**
	 * 当结果不为空时所调用的方法,子类重写该方法来处理结果
	 * 
	 * @param result
	 * @return
	 */
	public abstract void doStuffWithResult(Result result);

	/**
	 * 后台doInBackground中出现异常时,调用publishProgress()方法,该方法会
	 * 激活调用此方法,显示异常信息
	 */
	@Override
	protected void onProgressUpdate(WSError... values) {
		Toast.makeText(mActivity, values[0].getMessage(), Toast.LENGTH_LONG).show();
		this.cancel(true);
		mProgressDialog.dismiss();
		super.onProgressUpdate(values);
	}
}

WSError类代码如下:

package uk.ac.essex.musicplayer.api;

public class WSError extends Throwable {

	private static final long serialVersionUID = 1L;

	private String message;

	public void setMessage(String message) {
		this.message = message;
	}

	public String getMessage() {
		return message;
	}

}


你可能感兴趣的:(UI,String,null,Class,任务)