码迷,mamicode.com
首页 > 移动开发 > 详细

Android 异步任务 代码很简短,简单异步工具封装,方便执行异步任务

时间:2015-01-05 18:47:02      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

比较简单,就3个类。

1、创建一个单例的线程池,用来执行异步任务

<pre name="code" class="java">package com.ferris.pool;

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

public class FerrisPoolManager {
	private ExecutorService service;

	private FerrisPoolManager() {
		int num = Runtime.getRuntime().availableProcessors();
		service = Executors.newFixedThreadPool(num * 2);
	}

	private static FerrisPoolManager manager;

	public static FerrisPoolManager getInstance() {
		if (manager == null) {
			synchronized (FerrisPoolManager.class) {
				if(manager == null) {
				manager = new FerrisPoolManager();
				}
			}
		}
		return manager;
	}

	public void addTask(Runnable runnable) {
		service.execute(runnable);
	}
	public void cancelTask(){
		service.shutdown();
	}
}




2、定义一个任务接口

package com.ferris.pool;

public interface FerrisTaskListem {
	public void get();  //运行在线程里

	public void update(); //运行在主线程(从哪里new就是哪个线程,也不一定是主线程service等)
}



3、任务执行对象

package com.ferris.pool;

import android.os.Handler;
import android.os.Message;

public class FerrisTask {
	private FerrisTaskListem taskListem;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if(taskListem!=null){
				taskListem.update();
			}
		};
	};

	public FerrisTask(FerrisTaskListem taskListem) {
		this.taskListem = taskListem;
	}

	public void Execute(){
		FerrisPoolManager.getInstance().addTask(new RunTask());
	}
	
	public class RunTask implements Runnable {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if(taskListem!=null){
				taskListem.get();
			}
			Message message=Message.obtain();
			handler.sendMessage(message);

		}
	}

	
}


4、使用方法


FerrisTask ferrisTask = new FerrisTask(new FerrisTaskListem() {
			@Override
			public void update() {  //主线程
				// TODO Auto-generated method stub
				String name = Thread.currentThread().getName();
				System.out.print(name);
			}

			@Override
			public void get() { //UI线程
				// TODO Auto-generated method stub
				String name = Thread.currentThread().getName();
				System.out.print(name);

			}
		});
		ferrisTask.Execute();




Android 异步任务 代码很简短,简单异步工具封装,方便执行异步任务

标签:

原文地址:http://blog.csdn.net/xufeifandj/article/details/42425755

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!