android handler的post,Android-android mHandler.post()怎么用?什么情况下使用效果最好?...

这是一个典型的应用场景,UI线程因为有长时间的工作任务,新启一个线程去完成之后需要将结果返回到ui线程。这个时候因为工作线程无法直接访问ui控件来更新UI,便使用handler去间接通信。

class MyActivity extends Activity {

private Handler mHandler = new Handler();

private Runnable updateUI = new Runnable() {

public void run() {

//Do UI changes (or anything that requires UI thread) here

}

};

Button doSomeWorkButton = findSomeView();

public void onCreate() {

doSomeWorkButton.addClickListener(new ClickListener() {

//Someone just clicked the work button!

//This is too much work for the UI thread, so we'll start a new thread.

Thread doSomeWork = new Thread( new Runnable() {

public void run() {

//Work goes here. Werk, werk.

//...

//...

//Job done! Time to update UI...but I'm not the UI thread! :(

//So, let's alert the UI thread:

mHandler.post(updateUI);

//UI thread will eventually call the run() method of the "updateUI" object.

}

});

doSomeWork.start();

});

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值