很多时候我们需要对每个组件或者所有的UI线程要去负责View的创建并且维护它,例如更新冒个TextView的显示,都必须在主
线程中去做,我们不能直接在UI线程中去创建子线程,要利用消息机制:handler
本篇博客将带大家走进我们熟悉的Handler,顺带写了一个例子来验证Handler的消息机制,Handler通过对子线程的处理,实
现对UI的更新等操作
private TextView time; private Handler handler = new Handler(){ public void handleMessage(Message msg) { if(msg.what==Reflsh){ time.setText(String.valueOf(msg.obj)); } super.handleMessage(msg); }; }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); text = getResources().getStringArray(R.array.array); for(int i=0;i<text.length;i++){ Map<String,Object> map = new HashMap<String, Object>(); map.put("img", icon[i]); map.put("name", text[i]); list.add(map); } adapter = new SimpleAdapter(getActivity(), list, R.layout.log, new String[]{"img","name"}, new int []{R.id.g_icon,R.id.g_text}); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_shouye, container, false) ; gridview = (GridView)view.findViewById(R.id.gridView); time = (TextView)view.findViewById(R.id.time);//时间 ImageView icon = (ImageView)view.findViewById(R.id.icon);//头像 TextView name = (TextView)view.findViewById(R.id.name);//昵称 // File file = new File(Environment.getExternalStorageDirectory()+"/"+"weiinfo") ; BufferedReader reader = null ; String line = null ; try { reader = new BufferedReader(new FileReader(file)) ; line = reader.readLine() ; } catch (Exception e) { e.printStackTrace(); } data = line.split("\\*") ; Picasso.with(getActivity().getApplicationContext()).load(data[5]).into(icon); name.setText(data[0]); new Thread(new Runnable() { @Override public void run() { try { while(true){ Thread.sleep(1000); Message msg = new Message(); msg.what = Reflsh; msg.obj = new Date(System.currentTimeMillis()).toLocaleString(); Log.d("XXXXXXXXXXXXXX", msg.obj.toString()); handler.sendMessage(msg); } } catch (Exception e) { Log.d("异常", ""+e); } } }).start();
上面测试Handler的代码是来自MaoZhuaWeiBo的首页界面的动态北京时间演示,我写了一个Handler来处理我new 出来的子线程,在子线程里我每休眠一秒执行获取一次模拟器当前系统时间,并且将消息发送至Handler处理,Handler将消息更新view同步更新,并且不会阻塞主UI,这就是Handler消息机制的好处!
消息机制打印结果:
一直到关闭这个应用程序为止,打印结果才会停止,这就是Handler的消息机制了~
时间: 2024-10-11 13:26:27