您的位置:首页 > 移动开发 > Android开发

Android的Handler用法

2015-11-27 14:42 387 查看
Android中耗时的操作通常会放在一个子线程中来处理。因为子线程常常涉及到UI更新,但是当子线程中有涉及到操作UI的操作时,就会对主线程产生危险,也就是说,更新UI只能在主线程中更新,在子线程中操作是危险的。这个时候,Handler就出现了来解决这个复杂的问题。由于Handler运行在主线程中(UI线程中),它与子线程可以通过Message对象来传递数据,这个时候,Handler就承担着接受子线程传过来的(子线程用sedMessage()方法传递)Message对象(里面包含数据),把这些消息放入主线程队列中,配合主线程进行更新UI。以下摘自Android自带示例BluetoothChat中的代码:

    //以下代码为子线程ConnectedThread通过mHandler发送消息通知UI线程连接的蓝牙设备名称

       // Send the name of the connected device back to the UI Activity

        Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);

        Bundle bundle = new Bundle();

        bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());

        msg.setData(bundle);

        mHandler.sendMessage(msg); //mHandler为主线程即UI线程BluetoothChat传递过来的对象。

当UI主线程接收到通知消息后,mHandler通过重写handleMessage来对接收到的不同Message(通过what区别)进行处理,完成UI主线程的界面更新。

    // The Handler that gets information back from the BluetoothChatService

    private final Handler mHandler = new Handler() {

        @Override

        public void handleMessage(Message msg) {

            switch (msg.what) {

    

            case MESSAGE_DEVICE_NAME:

                // save the connected device's name

                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);

                Toast.makeText(getApplicationContext(), "Connected to "

                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();

                break;

            }

        }

    };
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: