今天测试视频资讯客户端,跟新UI是 LogCat 控制台出现了这样的错误:Only the original thread that created a view hierarchy can touch its views. 网上搜了一下才发现:原来android中相关的view和控件不是线程安全的,我们必须单独做处理。所以这里再次用到了Handler这个类来操作。到这里我才认识到(后知后觉) 原来自己前面已经使用过这种方式来跟新UI的操作。没想到这里就给忘了。这里记录下 省以后再忘记:
代码如下:
//Handler的使用跟新UI
final Handler handler = new Handler(){
public void handleMessage(Message msg){
switch (msg.what) {
case 0:
listView.setAdapter(adapter);
break;
default:
Toast.makeText(getApplicationContext(), R.string.error, 1)
.show();
break;
}
}
};
//使用线程加载数据
new Thread(new Runnable() {
@Override
public void run() {
try {
List<Video> videos = VideoService.getAll();//需修改成你本机的Http请求路径
List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
for(Video video : videos){
System.out.println("---------------------------------------==="+video);
HashMap<String, Object> item = new HashMap<String, Object>();
item.put("id", video.getId());
item.put("name", video.getName());
item.put("time", getResources().getString(R.string.timelength)
+ video.getTimelength()+ getResources().getString(R.string.min));
data.add(item);
}
adapter = new SimpleAdapter(getApplicationContext(), data, R.layout.items,
new String[]{"name", "time"}, new int[]{R.id.name, R.id.time});
handler.sendEmptyMessage(0);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
最后在来说下Handler这个类:
官方描述:A Handler allows you to send and process Message
and Runnable objects associated with a thread‘s MessageQueue
. Each Handler instance is associated with a single thread and that thread‘s message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
特点:
handler可以分发Message对象和Runnable对象到主线程中, 每个Handler实例,都会绑定到创建他的线程中(一般是位于主线程),
它有两个作用: (1): 安排消息或Runnable 在某个主线程中某个地方执行, (2)安排一个动作在不同的线程中执行
Handler中分发消息的一些方法
post(Runnable)
postAtTime(Runnable,long)
postDelayed(Runnable long)
sendEmptyMessage(int)
sendMessage(Message)
sendMessageAtTime(Message,long)
sendMessageDelayed(Message,long)
以上post类方法允许你排列一个Runnable对象到主线程队列中,
sendMessage类方法, 允许你安排一个带数据的Message对象到队列中,等待更新.
通过Handler更新UI实例:(这个是别人写的这里自己留着做个参考)
步骤:
1、创建Handler对象(此处创建于主线程中便于更新UI)。
2、构建Runnable对象,在Runnable中更新界面。
3、在子线程的run方法中向UI线程post,runnable对象来更新UI。