android编程:Handler的handleMessage在发送消息后没有立即被调用
界面一个ProgressBar,主线程用来更新进度,创建一个线程执行“任务”,把进度的值sendMessage出去,由handleMessage来更新进度条。发现把所有消...
界面一个ProgressBar,主线程用来更新进度,创建一个线程执行“任务”,把进度的值sendMessage出去,由handleMessage来更新进度条。发现把所有消息发完后,那些消息才开始被处理?求解,谢谢
public class MainActivity extends Activity {
Handler handler = null;
HandlerThread thread = null;
static ProgressBar bar = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("MainActivity",""+Thread.currentThread().getId());
bar = (ProgressBar)this.findViewById(R.id.progressBar1);
bar.setMax(100);
bar.setProgress(20);
thread = new HandlerThread("anotherThread");
thread.start();
handler = new MyHandler(thread.getLooper());
handler.post(new Runnable(){
public void run(){
Log.d("Thead",""+Thread.currentThread().getId());
for( int i=1; i<=100; i++)
{
handler.sendEmptyMessage(i);
Log.d("SendMessage", ""+i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
static class MyHandler extends Handler{
public MyHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d("HandleMessage",msg.toString() );
bar.setProgress(msg.what);
bar.refreshDrawableState();
}
}
}
消息都发送完了,才开始处理 展开
public class MainActivity extends Activity {
Handler handler = null;
HandlerThread thread = null;
static ProgressBar bar = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("MainActivity",""+Thread.currentThread().getId());
bar = (ProgressBar)this.findViewById(R.id.progressBar1);
bar.setMax(100);
bar.setProgress(20);
thread = new HandlerThread("anotherThread");
thread.start();
handler = new MyHandler(thread.getLooper());
handler.post(new Runnable(){
public void run(){
Log.d("Thead",""+Thread.currentThread().getId());
for( int i=1; i<=100; i++)
{
handler.sendEmptyMessage(i);
Log.d("SendMessage", ""+i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
static class MyHandler extends Handler{
public MyHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d("HandleMessage",msg.toString() );
bar.setProgress(msg.what);
bar.refreshDrawableState();
}
}
}
消息都发送完了,才开始处理 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询