1.创建新线程
2.创建消息对象,指定处理该消息的handler
3.设置消息的值
4.主线程指定的handler处理消息
<?xml version="1.0" encoding="UTF-8"?>
<words count="20">
<word>w001</word>
<word>w002</word>
<word>w003</word>
<word>w004</word>
<word>w005</word>
<word>w006</word>
<word>w007</word>
<word>w008</word>
<word>w009</word>
<word>w010</word>
<word>w011</word>
<word>w012</word>
<word>w013</word>
<word>w014</word>
<word>w015</word>
<word>w016</word>
<word>w017</word>
<word>w018</word>
<word>w019</word>
<word>w020</word>
</words>
private void changeProgressByHandler() {
new Thread(){
//得到XML资源解析器
XmlResourceParser xrp = getResources().getXml(R.xml.words) ;
int flag = 0 ;int progress = 0 ;int count = 0 ;
public void run(){
try {
while(true){
//创建消息对象,指定处理该消息的handler
Message msg = Message.obtain(wordHandler) ;
//得到下一步解析的事件
flag = xrp.next() ;
if(flag == XmlResourceParser.END_DOCUMENT){
break ;
}
if(flag == XmlResourceParser.START_TAG){
if("words".equals(xrp.getName())){
count = Integer.parseInt(xrp.getAttributeValue(0));
}
if("word".equals(xrp.getName())){
//当前解析的进度
progress = bar.getProgress()+bar.getMax()/count ;
String content = xrp.nextText() ;
words.add(content) ;
msg.arg1 = progress ;
adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1,words) ;
//将消息推送到handler
msg.sendToTarget();
sleep(1000) ;
}
}
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start() ;
}
private Handler wordHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int progress = msg.arg1 ;
MainActivity.this.setListAdapter(adapter);
bar.setProgress(progress);
}
};
ANR 应用程序无响应
原因:主线程被阻塞(activity中又叫UI线程)
解决方法:多线程
在非UI线程中不能改变视图控件的属性(多数视图控件不是线程安全的)