0
如果我想在從Web服務調用接收到消息時從後臺線程更新我的UI,下面將被視爲安全選項嗎?我擔心的是具有處理程序在我的應用程序類從Web服務中更新Android UI線程
public class MyApplication extends Application {
private static long uiThreadId;
private static Handler uiHandler;
@Override
public void onCreate() {
super.onCreate();
uiThreadId = Thread.currentThread().getId();
uiHandler = new Handler();
}
public static void customRunOnUiThread(Runnable action) {
if (Thread.currentThread().getId() != uiThreadId) {
uiHandler.post(action);
} else {
action.run();
}
} }
和潛在的內存泄漏,然後在與在獨立的線程接收的消息涉及的類:
new Thread(
new Runnable() {
@Override
public void run() {
// make web service call
MyApplication.customRunOnUiThread(new Runnable() {
@Override
public void run() {
httpResponseHandler.onSuccess();
}
});
}
}
}).start();
我的選擇是使用並行AsyncTasks在doInBackground方法中執行工作並更新onPostExecute方法中的UI。這兩個選項都有效,但我不確定哪一個是最「正確」的。
http://techboard.unden.at/allgemein/handler-vs-asynctask-vs-thread/和http:// stackoverflow.com/questions/6964011/handler-vs-asynctask-vs-thread –