Handler(2)

来源:互联网 发布:新网域名怎么设置ip 编辑:程序博客网 时间:2024/04/28 06:10

Handler是用来实现线程之间的通信的。

首先在主线程当中实现Handler的handleMessage()方法,然后在Worker Thread当中通过Handler发送消息。

下面以例子说明,在主界面当中创建一个TextView 和一个Button,用户点击按钮,两秒后TextView发生变化。该例子用于模拟从服务器中获取数据,再反馈给UI界面。


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="${packageName}.${activityClass}" >    <TextView        android:id="@+id/textViewId"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="数据" />    <Button         android:id="@+id/buttonId"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/textViewId"        android:text="发送消息"/></RelativeLayout>

MainActivity.java

package com.wyb.s02_e07_handler02;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity {private TextView textView;private Button button;private Handler handler;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textView = (TextView)findViewById(R.id.textViewId);button = (Button)findViewById(R.id.buttonId);handler = new MyHandler();button.setOnClickListener(new ButtonListener());}class MyHandler extends Handler{@Overridepublic void handleMessage(Message msg) {System.out.println("Thread-------->"+Thread.currentThread().getName());String s = (String)msg.obj;textView.setText(s);}}class ButtonListener implements OnClickListener{@Overridepublic void onClick(View v) {Thread t = new NetworkThread();t.start();}}class NetworkThread extends Thread{@Overridepublic void run() {System.out.println("Thread-------->"+Thread.currentThread().getName());//模拟访问网络,当运行线程时,先休眠2秒try {Thread.sleep(2*1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}//变量s的值模拟从网络中获取的数据String s = "从网络中获取的数据";//textView.setText(s);这样的做法是错误的,因为在Andorid系统当中,只有在Main Thread当中才能操作UIMessage msg = handler.obtainMessage();msg.obj = s;handler.sendMessage(msg);}}}

可以看到Handler对象是在主线程当中生成的,但在NetworkThread当中利用handler发送了一个msg给消息队列。然后再在handleMessage把该消息对象取出来。从而实现了Worker Thread 与 Main Thread 之间的通信。



0 0
原创粉丝点击