2 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個(gè)贊
我更喜歡使用AsyncTask來(lái)做。
從鏈接復(fù)制粘貼:
AsyncTask 可以正確且輕松地使用 UI 線程。此類允許您在 UI 線程上執(zhí)行后臺(tái)操作并發(fā)布結(jié)果,而無(wú)需操作線程和/或處理程序。
AsyncTask 被設(shè)計(jì)為圍繞 Thread 和 Handler 的輔助類,并不構(gòu)成通用的線程框架。理想情況下,AsyncTasks 應(yīng)該用于短期操作(最多幾秒鐘)。如果您需要讓線程長(zhǎng)時(shí)間運(yùn)行,強(qiáng)烈建議您使用 java.util.concurrent 包提供的各種 API,例如Executor、ThreadPoolExecutor 和 FutureTask。
說(shuō)了這么多,配置一個(gè) AsyncTask 還是蠻簡(jiǎn)單的,只需要?jiǎng)?chuàng)建一個(gè)像下面這樣的類:
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method works on the UI thread.
//this is the first to run before "doInBackground"
mTextView.setText("we start!");
}
@Override
protected String doInBackground(String... params) {
try {
//do whatever your async task needs to do. This method works async
//you can also call an UI callback from here with the publishProgress method. This will call the "onProgressUpdate" method, and it has to respect his type.
publishProgress("we go on!");
} catch (InterruptedException e) {
Thread.interrupted();
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
//this method works on the UI thread
//it get the "doInBackground" return value.
mTextView.setText(result);
}
@Override
protected void onPreExecute() {}
@Override
protected void onProgressUpdate(String... values) {
//this method works on UI thread, so it can access UI components and ctx
mTextView.setText(values[0]);
}
}
這是一個(gè)關(guān)于如何創(chuàng)建 AsyncTask 的基本示例,您可以像這樣使用它(表單活動(dòng)/片段):
AsyncTaskExample asyncTask = new AsyncTaskExample();
asyncTask.get(30000, TimeUnit.MILLISECONDS);
這將為您的異步操作設(shè)置超時(shí)。在這里查看確切的異常/返回
如有任何進(jìn)一步的問(wèn)題,請(qǐng)自由提問(wèn)。希望這可以幫助
編輯:
我只是注意到你AsyncTask的線程里面有一個(gè)。由于AsyncTask 已經(jīng)是 async,我會(huì)避免這樣做,只需AsyncTask使用我之前給您的方法調(diào)用。這樣,AsyncTask將運(yùn)行到給定的 TimeSpan :)

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
請(qǐng)參閱下面的代碼:它可能對(duì)您有所幫助。
CountDownTimer timer = new CountDownTimer(3000,1000) {
@Override
public void onTick(long l) {
}
@Override
public void onFinish() {
//return a message here;
}
};
timer.start();
如果你有一個(gè)異步任務(wù)。然后在doInBackground方法中執(zhí)行以下操作:
@Override
protected Void doInBackground(Void... voids) {
//simply do your job
CountDownTimer timer = new CountDownTimer(3000,1000) {
@Override
public void onTick(long l) {
}
@Override
public void onFinish() {
//return a message here;
return message;
}
};
timer.start();
return your_reult;
}
添加回答
舉報(bào)