Android的handler和callback机制

来源:互联网 发布:手机乐谱制作软件 编辑:程序博客网 时间:2024/05/20 16:42

Handler主要用来在线程之间的通信的机制。如在Activity或Service中需要接收其他线程的消息,则在需要接收消息的Activity或Service中需要实现Callback接口。下面是PowerManagerService中用于接收其他线程消息的handleMessage()的例子:

    private final class PowerManagerHandler extends Handler {        public PowerManagerHandler(Looper looper) {            super(looper, null, true /*async*/);        }        @Override        public void handleMessage(Message msg) {            switch (msg.what) {                case MSG_USER_ACTIVITY_TIMEOUT:                    handleUserActivityTimeout();                    break;                case MSG_SANDMAN:                    handleSandman();                    break;                case MSG_SCREEN_ON_BLOCKER_RELEASED:                    handleScreenOnBlockerReleased();                    break;                case MSG_CHECK_IF_BOOT_ANIMATION_FINISHED:                    checkIfBootAnimationFinished();                    break;            }        }    }

然后在创建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发送消息:

    private void shutdownOrRebootInternal(final boolean shutdown, final boolean confirm,            final String reason, boolean wait) {        if (mHandler == null || !mSystemReady) {            throw new IllegalStateException("Too early to call shutdown() or reboot()");        }        Runnable runnable = new Runnable() {            @Override            public void run() {                synchronized (this) {                    if (shutdown) {                        ShutdownThread.shutdown(mContext, confirm);                    } else {                        ShutdownThread.reboot(mContext, reason, confirm);                    }                }            }        };        // ShutdownThread must run on a looper capable of displaying the UI.        Message msg = Message.obtain(mHandler, runnable);        msg.setAsynchronous(true);        mHandler.sendMessage(msg);//向PowerManagerService发送message        // PowerManager.reboot() is documented not to return so just wait for the inevitable.        if (wait) {            synchronized (runnable) {                while (true) {                    try {                        runnable.wait();                    } catch (InterruptedException e) {                    }                }            }        }    

当执上面的代码之后,创建这个Handler(PowerManagerHandler)时使用Callback实例的handleMessage将会被调用。

 

可以使用如下代码将一个线程实例放入到Handler中使其执行:

            if(mHandler != null) {                mHandler.removeCallbacks(mStopDetectionTimeoutRunnable);                mHandler.postDelayed(mStopDetectionTimeoutRunnable, WAIT_FOR_DETECTION_TIMEOUT);            }

可使用如下代码删除这个线程:

        if(mHandler != null) {            mHandler.removeMessages(MSG_OPEN_LENOVO_SMART_STANDBY_CAMERA_SUCCESS);            mHandler.removeCallbacks(mStopDetectionTimeoutRunnable);        }

 Handler上还有许多类似的发送消息或添加线程的方法。

原创粉丝点击