android耗时任务_HandlerThread

HandlerThread 

在上一篇 android耗时任务_handler中介绍了handler的运作机制,并且介绍了一个普通线程中产生looper并使用handler机制通信的简单例子。我们知道在普通线程中是没有looper的,也就不好在普通线程空间中使用handler机制,如果每次都像上一篇的例子那样做的话就会略显麻烦。其实Android已经封装了一个拥有自己looper的线程HandlerThread,它的实现和上一篇中给出的例子基本一,只是更加专业一点。下面是此类的详细代码。
public class HandlerThread extends Thread {
    private int mPriority;  
    private int mTid =-1; 
    private Looper mLooper; 
 
    publicHandlerThread(String name) {
        super(name);
        mPriority =Process.THREAD_PRIORITY_DEFAULT;
    }
 
    publicHandlerThread(String name, int priority) {
        super(name);
        mPriority =priority;
    }
 
    protected void onLooperPrepared() {
    }
 
    public void run() {
        mTid =Process.myTid();
        Looper.prepare();
        synchronized(this) {
            mLooper =Looper.myLooper();
            notifyAll();   
        }
       Process.setThreadPriority(mPriority);
       onLooperPrepared();
        Looper.loop();  
        mTid = -1;
    }
 


    public Looper getLooper() {
        if (!isAlive()) {
            return null;
        }
 
        // If the threadhas been started, wait until the looper has been created.
        synchronized(this) {
            while(isAlive() && mLooper == null) {
                try {
                   wait();
                } catch(InterruptedException e) {
                }
            }
        }
        return mLooper;
    }
 
    public boolean quit(){
        Looper looper =getLooper();
        if (looper !=null) {
           looper.quit();
            return true;
        }
        return false;
    }
 


    public intgetThreadId() {
        return mTid;
    }
}
此类就是继承了Thread类,使用此类时一定要注意必须start(),否则run()方法没有调用,handler机制也就没有建立起来。

经典应用

对于HandlerThread的一个经典应用就是在service中的应用,我们知道,一般而言service是运行在主线程中的,在 android耗时任务_ANR中我也建议在BroadcastReceiver中启动service,在service中启动线程处理耗时任务。那么如何启动线程,下面给出一个经典的代码:

public class BackService extends Service {

	private ServiceHandler serviceHandler;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}


	private final class ServiceHandler extends Handler {


		public ServiceHandler(Looper looper) {
			super(looper);
		}


		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			onHandleIntent((Intent) msg.obj);
			// 在其参数startId跟最后启动该service时生成的ID相等时才会执行停止服务。
			stopSelf(msg.arg1);
		}
	}


	@Override
	public void onCreate() {
		super.onCreate();
		HandlerThread thread = new HandlerThread("BackService");
		thread.start();


		Looper serviceLooper = thread.getLooper();
		serviceHandler = new ServiceHandler(serviceLooper);
	}


	@Override
	public void onStart(Intent intent, int startId) {
		Message msg = serviceHandler.obtainMessage();
		msg.arg1 = startId;
		msg.obj = intent;
		serviceHandler.sendMessage(msg);
	}


	protected void onHandleIntent(Intent intent) {
               //做你的异步任务
	}
}





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值