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;
}
}
};
//以下代码为子线程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;
}
}
};
相关文章推荐
- android 如何预置APK
- Android手机在开发调试时logcat不显示输出信息的解决办法
- AndroidL 智能指针sp wp RefBase LightRefBase
- Android友盟微社区第三方集成
- Android调试----日志
- Android修改和添加APN网络
- 【Android】 查看周围wifi的ssid,并按信号强弱排序
- Android 键盘使用四(中文API)
- Android 键盘使用三(显示、隐藏、切换、数字键盘、英文数字键盘)
- 关于android 5.0对开发带来的影响
- Android创建桌面快捷方式所遇到的问题与解决方案
- Ant自动编译打包&发布 android项目
- Android数据库中增删改查数据
- Android中用注解和反射实现控件的绑定
- android 设置viewpager滑动速度
- Android Gallery
- Android lint删除无用资源文件
- Android编码时的一些实用小技巧
- Android登录实例——计时显示“隐视密码*”
- Android问题集锦之一:adb devices 出现unauthorized错误