>  기사  >  백엔드 개발  >  Weibo 개발 2 클라이언트 BaseTask 및 BaseTaskPool

Weibo 개발 2 클라이언트 BaseTask 및 BaseTaskPool

WBOY
WBOY원래의
2016-08-08 09:31:041002검색
  因为微博程序中客户端与服务器端的数据传递有时会耗时很长,所以采用多进程异步处理,就是界面UI与数据的发送接收不在一个进程里。每次数据传输的时候会开一个新的线程。
    BaseTask就是这个记录异步任务属性的类
package com.app.demos.base;

public class BaseTask {

	public static final int TASK_COMPLETE = 0;   //任务完成
	public static final int NETWORK_ERROR = 1;   //网络错误
	public static final int SHOW_LOADBAR = 2;    //显示下载条
	public static final int HIDE_LOADBAR = 3;    //不显示下载条
	public static final int SHOW_TOAST = 4;      //显示Toast
	public static final int LOAD_IMAGE = 5;      //加载图片
	
	private int id = 0;
	private String name = "";
	
	public BaseTask() {}
	
	public int getId () {
		return this.id;
	}
	
	public void setId (int id) {
		this.id = id;
	}
	
	public String getName () {
		return this.name;
	}
	
	public void setName (String name) {
		this.name = name;
	}
	
	public void onStart () {

	}
	
	public void onComplete () {

	}
	
	public void onComplete (String httpResult) {

	}
	
	public void onError (String error) {

	}
	
	public void onStop () throws Exception {

	}
	
}

다음은 Task Pool 관련 코드인 BaseTaskPool이다.

package com.app.demos.base;

import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.content.Context;
import com.app.demos.util.HttpUtil;

import com.app.demos.util.AppClient;

public class BaseTaskPool {
	
	// task thread pool
	static private ExecutorService taskPool;
	
	// for HttpUtil.getNetType
	private Context context;
	
	public BaseTaskPool (BaseUi ui) {                       //初始建立缓冲池
		this.context = ui.getContext();
		taskPool = Executors.newCachedThreadPool();
	}
	根据不同的需求重载了addTask方法三次
	// http post task with params
	public void addTask (int taskId, String taskUrl, HashMap<String, String> taskArgs, BaseTask baseTask, int delayTime) {
		baseTask.setId(taskId);
		try {
			<span>taskPool.execute(new TaskThread(context, taskUrl, taskArgs, baseTask, delayTime));</span>
		} catch (Exception e) {
			taskPool.shutdown();
		}
	}
	
	// http post task without params
	public void addTask (int taskId, String taskUrl, BaseTask baseTask, int delayTime) {
		baseTask.setId(taskId);
		try {
			<span>taskPool.execute(new TaskThread(context, taskUrl, null, baseTask, delayTime));</span>
		} catch (Exception e) {
			taskPool.shutdown();
		}
	}
	
	// custom task
	public void addTask (int taskId, BaseTask baseTask, int delayTime) {
		baseTask.setId(taskId);
		try {
			<span>taskPool.execute(new TaskThread(context, null, null, baseTask, delayTime));</span>
		} catch (Exception e) {
			taskPool.shutdown();
		}
	}
	异步创建任务进程
	// task thread logic
	private class TaskThread implements Runnable {
		private Context context;
		private String taskUrl;
		private HashMap<String, String> taskArgs;
		private BaseTask baseTask;
		private int delayTime = 0;
		public TaskThread(Context context, String taskUrl, HashMap<String, String> taskArgs, BaseTask baseTask, int delayTime) {
			this.context = context;
			this.taskUrl = taskUrl;
			this.taskArgs = taskArgs;
			this.baseTask = baseTask;
			this.delayTime = delayTime;
		}
		@Override
		public void run() {
			try {
				baseTask.onStart();
				String httpResult = null;
				// set delay time
				if (this.delayTime > 0) {
					Thread.sleep(this.delayTime);
				}
				try {
					// remote task
					if (this.taskUrl != null) {
						// init app client
						AppClient client = new AppClient(this.taskUrl); // 用到了上一讲的AppClient封装了基本的http 的post与get方法
						if (HttpUtil.WAP_INT == HttpUtil.getNetType(context)) {
							client.useWap();
						}
						// http get
						if (taskArgs == null) {
							httpResult = client.get();
						// http post
						} else {
							httpResult = client.post(this.taskArgs);
						}</span>
					}
					// remote task
					if (httpResult != null) {
						baseTask.onComplete(httpResult);
					// local task
					} else {
						baseTask.onComplete();
					}
				} catch (Exception e) {
					baseTask.onError(e.getMessage());
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					baseTask.onStop();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}


위 내용은 Weibo Development 2 클라이언트의 BaseTask와 BaseTaskPool을 관련 내용을 포함하여 소개한 내용으로, PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.