HandlerThread怎麼更新ui,我試了很多方法,都不能更新ui,求大神們指導一下
HandlerThread handlerThread = new HandlerThread(getMainLooper().toString());
handlerThread.start();
MyHandler myHandler = new MyHandler(handlerThread.getLooper());
Message message = myHandler.obtainMessage();
message.sendToTarget();
public class MyHandler extends Handler {
public MyHandler(Looper looper){
super(looper);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
}
在handleMessage(Message msg)方法裡怎麼不能更新ui
handler.send(Message message),或者handler.post (Runnable r);
2.View.post(Runnable r);
/**
*/
class ViewPostThread extends Thread{
@Override
public void run() {
super.run();
while(count<101){
/**
* view.post(Runnable)
*/
bar.post(new Runnable() {
@Override
public void run() {
isChanging = true;
bar.setProgress(count);
count++;
}});
/**
* view.postDelayed(Runnable,delayTime)
*/
// bar.postDelayed(new Runnable() {
//
// @Override
// public void run() {
// isChanging = true;
// bar.setProgress(count);
// count++;
//
// }},100);
//
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
3.Activity的RunOnUIThread(Runnable r);
class ViewPostThread extends Thread{
@Override
public void run() {
super.run();
while(count<101){
runOnUiThread(new Runnable() {
@Override
public void run() {
isChanging = true;
bar.setProgress(count);
count++;
}});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
4.通過HandlerThread進行更新
/**
*/
private HandlerThread handlerThread =new HandlerThread("handler_thread"){
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
count++;
bar.setProgress(count);
if(count==100){
Toast.makeText(HandlerThreadTest.this, "Done", 1).show();
}
};
};
使用時候調用
handlerThread.start();
5.在子線程中更新,前提是得Loop.prepare( );
/**
*/
class NormalThread extends Thread{
private int count=0;
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
count++;
bar.setProgress(count);
};};
@Override
public void run() {
super.run();
Looper.prepare();
while(count<=100){
handler.sendEmptyMessage(0);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Looper.loop();
}
}