学习在新线程中使用Handler更新UI的方法:
package com.example.hnadlerapp;
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 text;
private Button button;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView)findViewById(R.id.text);
button = (Button)findViewById(R.id.button);
text.setText("通过线程连接...");
button.setOnClickListener(new ButtonListener());
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
String s;
s = (String)msg.obj;
text.setText(s);
}
};
class ButtonListener implements OnClickListener {
@Override
public void onClick(View arg0) {
Mythread thread = new Mythread();
thread.start();
}
}
class Mythread extends Thread {
public void run() {
try {
Thread.sleep(2000);
} catch(Exception e) {
e.printStackTrace();
}
String s = "返回成功";
//从handler的obtainMessage方法取得消息对象
Message msg = handler.obtainMessage();
//把字符串给消息对象的object
msg.obj = s;
//调用handler的sendMessage方法把消息对象传入后,系统自动调用handler 的handleMessage方法
handler.sendMessage(msg);
}
}
}
全部代码:
package com.example.hnadlerapp;
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 text;
private Button button;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView)findViewById(R.id.text);
button = (Button)findViewById(R.id.button);
text.setText("通过线程连接...");
button.setOnClickListener(new ButtonListener());
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
String s;
s = (String)msg.obj;
text.setText(s);
}
};
class ButtonListener implements OnClickListener {
@Override
public void onClick(View arg0) {
Mythread thread = new Mythread();
thread.start();
}
}
class Mythread extends Thread {
public void run() {
try {
Thread.sleep(2000);
} catch(Exception e) {
e.printStackTrace();
}
String s = "返回成功";
Message msg = handler.obtainMessage();
msg.obj = s;
handler.sendMessage(msg);
}
}
}