Handler主要用来在线程之间的通信的机制。如在Activity或Service中需要接收其他线程的消息,则在需要接收消息的Activity或Service中需要实现Callback接口。下面是PowerManagerService中用于接收其他线程消息的handleMessage()的例子:
然后在创建Handler的地方将实现了Callback的类的实例传入:
public void init(Context context, LightsService ls,
ActivityManagerService am, BatteryService bs, IBatteryStats bss,
DisplayManagerService dm) {
mContext = context;
mLightsService = ls;
mBatteryService = bs;
mBatteryStats = bss;
mDisplayManagerService = dm;
mHandlerThread = new HandlerThread(TAG);
mHandlerThread.start();
mHandler = new PowerManagerHandler(mHandlerThread.getLooper());//将实现了Callback类的实例传入
Watchdog.getInstance().addMonitor(this);
// Forcibly turn the screen on at boot so that it is in a known power state.
// We do this in init() rather than in the constructor because setting the
// screen state requires a call into surface flinger which then needs to call back
// into the activity manager to check permissions. Unfortunately the
// activity manager is not running when the constructor is called, so we
// have to defer setting the screen state until this point.
mDisplayBlanker.unblankAllDisplays();
}
然后当在线程中可使用如下代码向PowerManagerService发送消息:
当执上面的代码之后,创建这个Handler(PowerManagerHandler)时使用Callback实例的handleMessage将会被调用。
可以使用如下代码将一个线程实例放入到Handler中使其执行:
可使用如下代码删除这个线程:
Handler上还有许多类似的发送消息或添加线程的方法。