非UI thread更新UI的方式

Android的UI thread并非线程安全,因此所有UI的操作必须在UI thread完成。

主要方法有:

1,使用AsyncTask,

AsyncTask中的onXxxxx callback都在UI thread中执行,

后台任务在doInBackground方法中执行完成后会把结果传递给onPostExecute,

可以在onPostExecute中更新UI

2,使用Handler

非UI thread可以向UI thread的Handler发message,Handler收到message后更新UI.

在work thread中使用如下方法可以拿到UI thread的handler

Handler n = new Handler(Looper.getMainLooper()){

    public void handleMessage(Message m){ }

}


3,activity的runOnUiThread(Runnable r)方法

在非UI thread中

mActivity.runOnUiThread( new Runnable() {

    public void run() {

        //操纵UI

    }

});

4,view的post和postDelay方法

在非UI thread中

mImageView.post( new Runnable(){

    public void run() {

        //操纵mImageView

    }

});





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值