我有一個文本字段(EditText
),並在事件onTextChanged
對每一個文本的改變我發送一個HTTP查詢在一個單獨的線程。我需要從後臺線程更新UI。與用戶互動用戶界面和從後臺線程更新UI
一切都很好,我知道如何從後臺線程更新UI,但是當用戶在文本字段中鍵入文本時,鍵盤沒有響應每個水龍頭(通過時間)並且結果中沒有寫入整個文本文本字段。它只有在後臺線程更新UI時纔會發生。
我試圖爲後臺線程低優先級,但沒有什麼:(
我不知道是什麼我'做錯了,幫我:)
//Create a background thread on UI thread
ex = new ExampleThread2(this, text);
ex.start();
//ExampleThread2.java
public class ExampleThread2 extends Thread implements Handler.Callback {
private static final String LOG_TAG = ExampleThread2.class.getSimpleName();
Semaphore s = new Semaphore(0);
public static final int BEGIN_TASK = 1;
public static final int END_TASK = 2;
private boolean running = true;
public Handler mLoaderHandler;
public TModel mLoaderCallback;
public ExampleThread2(TModel callback, String text) {
this.mLoaderCallback = callback;
}
void sendMessage(int message){
Message msg = mLoaderHandler.obtainMessage();
msg.what = message;
mLoaderHandler.sendMessage(msg);
}
@Override
public void run(){
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//HandlerThread myHandlerThread = new HandlerThread("MyHandlerThread", Process.THREAD_PRIORITY_BACKGROUND);
//myHandlerThread.start();
this.mLoaderHandler = new Handler(Looper.getMainLooper(), this);
do {
sendMessage(BEGIN_TASK); //Updates UI
start2(); //main work
sendMessage(END_TASK); //Updates UI
try {
s.acquire();
if(s.availablePermits() > 0){
s.acquire(s.availablePermits());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} while(running);
// Tell the handler thread to quit
//myHandlerThread.quit();
}
@Override
public boolean handleMessage(final Message msg) {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
switch (msg.what) {
case BEGIN_TASK:
mLoaderHandler.post(new Runnable() {
@Override
public void run() {
updateUI();
}
});
break;
case END_TASK:
mLoaderHandler.post(new Runnable() {
@Override
public void run() {
updateUI();
}
});
break;
} }
使用[AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html)使事情變得相當容易。 – Nate