Android Handler(六)
本帖最后由 4546 于 2011-8-10 10:30 编辑
java代码:
Log.d("ThreadId", "onCread:" + String.valueOf(Thread.currentThread().getId()));
myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case 0: Bundle date=msg.getData();
txt.setText(String.valueOf(date.getInt("time")));
Log.d("ThreadId", "HandlerMessage:" + String.valueOf(Thread.currentThread().getId()));
Log.d("ThreadId", "msgDate:" + String.valueOf(date.getInt("time")));
break;
}
}
};
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStartTime:
//myHandler.post(this);
myHandler.postDelayed(this, 1000);
break;
case R.id.btnStopTime:
break;
}
}
@Override
public void run() {
while(true) {
total--;
if(total<0) break;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Message msg=new Message();
Bundle date = new Bundle();
// 存放数据
date.putInt("time", total);
msg.setData(date);
msg.what=0;
Log.d("ThreadId", "POST:" + String.valueOf(Thread.currentThread().getId())); myHandler.sendMessage(msg);
Log.d("ThreadId", "Thread:" + String.valueOf(Thread.currentThread().getId()));
}
}
}
使用POST的方式 是将Runnable 一起发送给处理的线程(这里为UI),如果Runnable的操作比较耗时的话那线程将进入阻塞状态。可以看到先运行 Runnable的Run方法 然后在进入 HandleMessage() 。我还尝试了另一种写法,将TimerThreadPOST过去,运行结果是一样的。