我有一個功能,查詢網絡服務器來回幾個「ping pongs」,並寫了一個自定義處理程序來處理我的主UI線程和通信線程(我爲此使用AsyncTask,但隨着程序變得更加複雜,我決定在主要活動之外將通信代碼移除到自己的類)。Android的啓發(一個線程內的線程)
從onCreate觸發此線程通信的單個實例完美工作,沒有問題。 我希望這個查詢在常規時間基礎上運行 - 在後臺運行 - 整個應用程序正在使用時,所以我建立了另一個名爲pollTimer的線程,我試圖用它來調用其他線程定期進行。 顯然,它崩潰了,或者我不會發布這個。
有沒有辦法在線程中獲得線程?換句話說,從另一個線程觸發一個線程?
Timer pollTimer = new Timer();
private void startPollTimer(){
pollTimer.scheduleAtFixedRate(new TimerTask(){
public void run(){
Log.d(TAG,"timer dinged");
//if the following is commented out, this "dings" every 6 seconds.
//if its not commented out, it crashes
threadedPoll();
}
}, 3120, 6000);
}
private void threadedPoll() {
testThread(asciiQueries,WorkerThreadRunnable.typeLogin);
}
編輯:它可能會幫助包括「testThread」功能,從所謂的onCreate在以其自身的工作原理,但並不能使它從定時調用時。 「WorkerThreadRunnable」是它自己類中的大量代碼,它已經替代了AsyncTask在主要活動中處理它的混亂。
private Handler runStatHandler = null;
Thread workerThread = null;
private void testThread(String[] threadCommands, int commandType){
if(runStatHandler == null){
runStatHandler = new ReportStatusHandler(this);
if(commandType == WorkerThreadRunnable.typeLogin){
workerThread = new Thread(new WorkerThreadRunnable(runStatHandler,threadCommands, WorkerThreadRunnable.typeLogin));
}
workerThread.start();
return;
}
//thread is already there
if(workerThread.getState() != Thread.State.TERMINATED){
Log.d(TAG,"thread is new or alive, but not terminated");
}else{
Log.d(TAG, "thread is likely deaad, starting now");
//there's no way to resurrect a dead thread
workerThread = new Thread(new WorkerThreadRunnable(runStatHandler));
workerThread.start();
}
}
謝謝@JRaymond,我遇到的問題其實是一個與「無法在timerTask中調用Looper.prepare()」的線程中創建處理程序相關的崩潰。 從定時器中調用threadedPoll()的第二個,觸發上述操作。 如果我完全跳過計時器,並且只需在onCreate中運行「testThread(asciiQueries,WorkerThreadRunnable.typeLogin)」,則該自定義可運行/處理程序組合工作。它被Timer所調用,正在被它調用 – Octoth0rpe 2012-04-17 21:46:20
@ Octoth0rpe啊,好吧......我認爲它是因爲你的計時器線程是試圖聲明Handler的那個 - 這是不允許的B/C它不是爲處理程序設置的線程。無論線程調用處理程序的構造函數,都是處理程序所綁定的線程。所以如果你可以找到一種方法來調用工作線程中的構造函數,或者調用你自己的計時器線程...... – JRaymond 2012-04-17 21:55:39