您需要在活動類中創建一個擴展AsyncTask
的類。
UpdateDBTask task = new UpdateDBTask();
task.execute(someString);
在你的異步任務可以定義3個變量 - (所有這些都不可能是原始:意int
例如必須是Integer
)。
首先是您發送給異步任務對象以在doInBackground()
中使用的內容。 其次是你用來更新你的主線程onProgressUpdate()
。 三是doInBackground()
返回,將得到並用於顯示結果(再次 - 在主線程中)。你不必使用其中的任何一個(在我給你的代碼中使用LIKE),但是在擴展AsyncTask
時必須寫入類型。
public class UpdateDBTask extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
//Everything written here will happen in main thread before doInBackground() starts.
}
@Override
protected String doInBackground(String... params) {
//Do your things in different thread, allowing the main
//thread change things on GUI (Like showing toast...)
return null;
}
@Override
protected void onPostExecute(String result) {
//Everything you do here happens in the main thread AFTER doInBackground() is done.
}
}
您可以執行阻斷UI線程操作(例執行netwok操作等),所以麪包不會顯示出來utill UI線程可以自由 – Pragnani 2013-04-28 15:32:25
嘗試使用的AsyncTask爲您的網絡操作或數據庫更新,並在onPreExecute()' – Houcine 2013-04-28 15:45:40
中顯示你的Toast會不會有一個while循環有這種效果? – 2013-04-28 15:55:05