Android开发中如何使用多线程
展开全部
handler其实就是消息处理机制。首先在主线程也就是UI创建一个Handler对象,复写其中的handMessage( Message msg)方法。该方法里的msg就是子散晌线程发来的消息,表示子线程处理完了,以这个msg来兆衡通知主线程。让主线程来作UI的绘制工作。
那么子线程工作完了就要发消息了,比如:
run(){
data = getDataFromInternet();//耗时工作
Message msg = handler.obtainMessage(0, data);//通过handler得到消息,该消息的标识为0,消息内容是data
handler.sendMessage(msg);//发送
}
然后handler在主线程就负责接收:
public Handler handler = new Handler(){//处理UI绘制
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
data = (List<Map<String, Object>>) msg.obj;
if(data == null){
Toast.makeText(AllMovieActivity.this, "网络连接失败,获取不到影片族掘做信息", 1).show();
}else {
adapter = new HotMoviedapter(AllMovieActivity.this, data, R.layout.allmovielist_item,
new String[] { "picurl", "chname", "director", "leadrole",
"fshowtime", "country" }, new int[] { R.id.picurl,
R.id.chname, R.id.director, R.id.leadrole,
R.id.fshowtime, R.id.country },mListView);
TextView v = new TextView(AllMovieActivity.this);
v.setHeight(80);
v.setSelectAllOnFocus(false);
mListView.addFooterView(v);
mListView.setAdapter(adapter);
}
break;
default:
break;
}
}
};
那么子线程工作完了就要发消息了,比如:
run(){
data = getDataFromInternet();//耗时工作
Message msg = handler.obtainMessage(0, data);//通过handler得到消息,该消息的标识为0,消息内容是data
handler.sendMessage(msg);//发送
}
然后handler在主线程就负责接收:
public Handler handler = new Handler(){//处理UI绘制
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
data = (List<Map<String, Object>>) msg.obj;
if(data == null){
Toast.makeText(AllMovieActivity.this, "网络连接失败,获取不到影片族掘做信息", 1).show();
}else {
adapter = new HotMoviedapter(AllMovieActivity.this, data, R.layout.allmovielist_item,
new String[] { "picurl", "chname", "director", "leadrole",
"fshowtime", "country" }, new int[] { R.id.picurl,
R.id.chname, R.id.director, R.id.leadrole,
R.id.fshowtime, R.id.country },mListView);
TextView v = new TextView(AllMovieActivity.this);
v.setHeight(80);
v.setSelectAllOnFocus(false);
mListView.addFooterView(v);
mListView.setAdapter(adapter);
}
break;
default:
break;
}
}
};
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询