很多新手在启动新线程更新view时会出现
“Only the original thread that created a view hierarchy can touch its views”
以下是正确做法
“Only the original thread that created a view hierarchy can touch its views”
以下是正确做法
第一步:
/* 启动Thread */
new Thread(mTasks).start();
第二部:
private Runnable mTasks = new Runnable()
{
public void run()
{
while (run)
{
try
{
Thread.sleep(IntervalSec * 1000);
/* 传送Message给Handler */
mHandler.sendMessage(mHandler.obtainMessage());
//传送数据
/*
Bundle data = new Bundle();
data.putString("aa","ttt");
Message msg = new Message();
msg.setData(data);
mHandler.sendMessage(msg);
*/
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
第三步:
Handler mHandler = new Handler()
{
public void handleMessage(Message msg)
{
super.handleMessage(msg);
getYamWeatherPic();//此处更新view内容
//Log.d("--------", msg.getData().getString("aa"));
}
};
本文介绍了一种在Android应用中使用新线程更新UI的方法。通过创建并启动新线程,利用Handler机制发送消息到主线程,从而实现安全地更新界面元素。此方法避免了因非主线程修改UI组件而引发的错误。

被折叠的 条评论
为什么被折叠?



