2015-01-17 31 views
0

學習Android開發。 在轉到for循環中的下一個語句之前,代碼必須等待幾秒/分鐘/小時。如何在任何循環內使用「等待」命令?

for(i=0; i<number; i++) { 

    // Do Something 

    // Then Wait for x hours, y minutes, and z seconds. Then proceed to next command. 

    // Do some more things. 

} //End for loop. 

我搜索了這一點,但發現很多答案像thread.SleepSleeptry{wait(); } Catch{ },等...

此外,發現了Handler。我可以在for循環內使用Handler嗎?相反,是否有像wait(x小時,x分鐘,x秒)這樣的簡單命令;像這樣?

請幫忙!!

+0

你更好的使用。 new Handler()。postDelayed(new Runnable(){ @Override public void run(){ } },10000);.這將等待10秒鐘。我認爲這比使用睡眠或定時器更好 –

+0

你不想在主線程中這樣做,它會阻止用戶界面並使其無響應。在其他線程中,您可以使用睡眠。 – Henry

+0

我建議查看'AlarmManager'和'WakefulBroadcastReceiver'連同'Service'(或'IntentService',如果任務很短)。把它分解成更小的任務。 –

回答

2

這取決於你在哪裏有循環。如果你在主線程中運行循環,你不能「插入延遲」,因爲它會阻止執行,Java沒有任何東西像C#的async & await「輕鬆」解決這個問題。所以,最簡單的方法是:首先,將整個循環移動到後臺線程。 然後,您可以在需要延遲的地方使用Thread.sleep(…)。但是,如果您需要更新UI,您不能直接從後臺線程執行此操作,則需要使用Handler,調用post(Runnable)方法(傳遞的Runnable將在主線程上運行),並且在該Runnable中您必須檢查如果UI仍然存在(因爲用戶可以「關閉」應用程序,所以你的活動/片段/視圖/任何可以完成或處於「壞」狀態)

0
Thread.sleep(time_in_miliseconds) 

看起來是最簡單的解決方案。這是一個靜態方法,所以你不需要Thread類的實例。

+0

這很糟糕。將主(UI)線程置於睡眠狀態是不好的,它會凍結UI。永遠不要這樣做! –

0

等待是一種監視器方法,這意味着您可以從同步塊或方法調用該方法。 爲你的情況使用睡眠。

0

我在過去做過Android編程,但不是最近。儘管我已經做了很多Java,並且認爲我仍然會有所幫助。

對於處理程序,看起來你可以做到這一點。查看了文檔http://developer.android.com/reference/android/os/Handler.html#handleMessage(android.os.Message),本質上你是從一個線程發佈消息或可運行的消息,並在不同的線程中處理消息。你的for循環不會停止,因爲當你使用一個處理程序時你正在開始一個新的線程。

當創建一個處理程序時,如果它是消息或發佈了一個可發送的runnable,則需要重寫handleMessage(Message msg)方法,因爲這是在合適的時間已經過去之後調用的方法。要在特定時間或延遲時間後發送消息,您需要postAtTime,postDelayed,sendMessageAtTime和sendMessageDelayed方法(無論哪個方法需要)。

new Handler() { 

    public void handleMessage(Message msg) { 
     // Your code here. 
    } 

}.sendMessageDelayed(yourMessage, theAmountOfTimeInMilles); 

而且,您的信息進行處理後,如果你想要做的任何用戶界面更新(換句話說,更改任何圖形,如更新標籤或更改背景),您需要使用runOnUiThread方法,否則會拋出異常:

runOnUiThread(new Runnable() { 
    public void run() { 
     // Code including UI code here. 
    } 
}); 
+0

Handler已經處理了UI線程中的所有內容,並且使用'postDelayed'方法更容易 –

1

在Android中有一個類可以做所有你說的,AsyncTask。

private class YourTaskClassName extends AsyncTask<Void, Integer, Long> { 
protected Long doInBackground(Void.. values) { 
    //Here is where you do the loop 
    for (int i = 0; i < number; i++) { 
     ... 
     publishProgress(yourProgress); //Value passed to onProgressUpdate 
    } 

    return totalSize; //Value for onPostExecute 
} 

protected void onProgressUpdate(Integer... progress) { 
    //Here is what you wanna show while your loop is running in background 
    setProgressPercent(progress[0]); 
} 

protected void onPostExecute(Long result) { 
    //Here is what you wanna do when your loop has finished 
} 

}

你可以這樣調用new YourTaskClassName().execute();