这次学习一些线程方面的知识:
大家都知道,androidUI更新必须在主线程
下面用线程知识实现一个倒计时的效果:
下面这个如果把for循环里面的handler.sendEmptyMessage(-9);
换成下面的形式
Message message = new Message();
message.what = -9;
handler.sendMessage(message);
传递信息为什么不行?
必须使用handler.sendEmptyMessage(-9);才行谁知道为什么?
public class MainActivity extends Activity {
private MyView myView;
private Button mybutton;
private TextView mytextview;
public static final int UPDATE_TEXT = 1;
int i = 20;
Message message = new Message();
private Handler handler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case -9:
myView.setSweepValue(25);
mybutton.setText(i+"");
mytextview.setText(i+"");
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myView = (MyView) findViewById(R.id.myview);
mybutton = (Button) findViewById(R.id.mybutton);
mytextview = (TextView) findViewById(R.id.mytextview);
mybutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for(;i<=100;i+=10){
if (i>=100) {
break;
}
handler.sendEmptyMessage(-9);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
});
}
}