您的位置:首页 > 移动开发 > Android开发

android中handler的使用

2016-03-14 20:28 567 查看
       
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar= (ProgressBar) findViewById(R.id.progress);
button= (Button) findViewById(R.id.button);
handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
progressBar.setProgress(msg.arg1);
handler.post(new HandlerThread());
Bundle data=msg.getData();
button.setText(data.getString("data"));
}
};
Toast.makeText(MainActivity.this,Thread.currentThread().getName(),Toast.LENGTH_SHORT).show();
}

public void onClick(View view)
{
progressBar.setVisibility(View.VISIBLE);
handler.post(new HandlerThread());//这里并没有新开线程,还是在主线程中
}

private class HandlerThread implements Runnable{
@Override
public void run() {
Message message=handler.obtainMessage();//从消息队列中返回一个消息
message.arg1=i+=10;
handler.sendMessage(message);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i==100)
{
Message msg=handler.obtainMessage();
Bundle bundle=new Bundle();
bundle.putString("data","测试数据");
msg.setData(bundle);
msg.sendToTarget();
handler.removeCallbacks(new HandlerThread());
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, Thread.currentThread().getName(), Toast.LENGTH_SHORT).show();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android