任何人都可以在此向我指出正確的方向嗎?從後臺處理程序線程傳遞處理程序到後臺線程
我有派生兩個線程的活動,處理郵件,用活套
public static class MiddleThread extends Handler{
static public Handler handler;
public void run() {
Looper.prepare();
Log.d("MiddleThread", "Looper is prepared !");
handler = new Handler() {
public void handleMessage(Message msg)
{
Bundle bundle = msg.getData();
String exitString = bundle.getString("endmessage");
if(exitString.equals(("ExitOK")))
{
boolean searchFinished = true;
Looper looper = Looper.myLooper();
looper.quit();
} else
{
int fileCount = bundle.getInt("filecount");
String fileName = bundle.getString("filename");
Log.d("MiddleThread", "File Number " + fileCount + " is " + fileName);
}
}
};
Log.d("MiddleThread", "nandler should be initialised");
Looper.loop();
}
線程...那麼它產生的主要工作線程,它是從UI線程通過處理程序,和來自上述線程的處理程序。
public class BasicSearch {
public Handler handlerUi, handlerMiddleThread;
public Message messageUi, messageMiddleThread;
public int fileCount = 0;
public BasicSearch(Handler ui, Handler mt) {
handlerUi = ui;
handlerMiddleThread = mt;
}
public void listFiles()
{
File searchPath = Environment.getExternalStorageDirectory();
messageUi = handlerUi.obtainMessage();
messageMiddleThread = handlerMiddleThread.obtainMessage();
walk(searchPath);
Bundle b = new Bundle();
b.putString("endmessage", "ExitOK");
messageMiddleThread.setData(b);
handlerMiddleThread.dispatchMessage(messageMiddleThread);
}
private void walk(File path) {
File[] list = path.listFiles();
for(File f : list)
{
if(f.isDirectory())
{
walk(new File(f.getAbsolutePath()));
} else {
processFile(f);
}
}
}
private void processFile(File f) {
Bundle b = new Bundle();
fileCount++;
b.putString("filename", f.getName());
b.putInt("filecount", fileCount);
messageMiddleThread.setData(b);
Log.d("BasicSearch", "Data is set, to send to MiddleThread");
handlerMiddleThread.dispatchMessage(messageMiddleThread);
Log.d("BasicSearch", "Message sent");
}
}
無論發生什麼事,當它試圖在DispatchMessage,handlerMiddleThread恢復到被空。我甚至在我的活動中有下面的代碼,試圖確保它不是null,但是當我發送消息時它仍然最終爲null。
startMiddleThread();
while(true)
{
if(MiddleThread.handler != null)
break;
}
startSearchThread();
這是一個測試項目,因爲我希望能夠在繼續使用我的項目之前正確理解Handler/Looper概念。
我已經成功設法在我的UI線程中使用了一個處理程序,但是我的當前項目在UI中進行的處理過多,我想要一個輔助線程處理searchThread的輸出,並且只接收線程完成時UI線程中的消息。
將您的活動代碼與您稱爲'run'和'new BasicSearch'的代碼一起發佈。 – njzk2