主程序:
package com.example.demo_test;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView tvShow;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvShow = (TextView) findViewById(R.id.tv_show);
new Thread(new ThreadChangeUI(handler)).start();
}
// handler类接收数据
Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
// 动态更新UI界面
String str = msg.getData().getInt("num") + "";
System.out.println("str----------------->" + str);
tvShow.setText(str);
}
};
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
线程:
package com.example.demo_test;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class ThreadChangeUI implements Runnable {
private Handler handler;
private int num = 0;
public ThreadChangeUI(Handler handler) {
// TODO Auto-generated constructor stub
this.handler = handler;
}
@Override
public void run() {
// 每秒改变textview的值
while (true) {
try {
Thread.sleep(1000);
Message msg = new Message();
msg.what = 1;
// handler传递参数
// handler.sendMessage(msg);
Bundle bundle = new Bundle();
bundle.putInt("num", num++);
System.out.println("num---------->" + num);
msg.setData(bundle);
handler.sendMessage(msg);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("thread error...");
}
}
}
}