这篇是讲 workthread 模拟向网络访问数据,获得数据后,返回 message 发送给 mainthread ,并修改 textview 的 text。
1、layout:
<TextView
android:id="@+id/textViewId"
android:layout_width="match_parent"
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="发送消息" />2、activity:package com.away.b_07_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;
@Override
protected 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 {
@Override
public void handleMessage(Message msg) {
System.out.println("handlerMessage ---->> :" + Thread.currentThread().getName());
String s = (String) msg.obj;
textView.setText(s);
}
}
class ButtonListener implements OnClickListener {
@Override
public void onClick(View arg0) {
Thread t = new NetworkThread();
t.start();
}
}
class NetworkThread extends Thread {
@Override
public void run() {
System.out.println("network ---->> :" + Thread.currentThread().getName());
// 模拟访问网络,所以说当线程休眠时,首先休眠2秒钟
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 变量s的值,模拟从网络当中获取的数据
String s = "网络当中获取的数据";
// textView.setText(s); 这种做法是错误的,因为在android系统当中,只有mainthread当中才能操作UI
Message msg = handler.obtainMessage();
msg.obj = s;
// sendMessage()方法,无论是在主线程当中发送还是在workers thread当中发送,都是可以的
handler.sendMessage(msg);
}
}
}
1
原文:http://blog.csdn.net/ycwol/article/details/42066449