1 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超4個(gè)贊
在 Android 上,您必須在 UI 線程上運(yùn)行所有 UI 代碼。AsyncTask 中的代碼在其他線程中執(zhí)行,因此它不能調(diào)用 UI 方法。
為此,您應(yīng)該使用 Handler(代碼將在 UI 線程中調(diào)用): https ://developer.android.com/reference/android/os/Handler
final Handler h=new Handler();
h.postDelayed(new Runnable() {
public void run() {
printPrice(price);
price = price + 0.05;
h.postDelayed(this, 1000); // call for next update
}
}, 1000);
我你必須使用 AsyncTask,那么你應(yīng)該從方法更新 UI:onProgressUpdate https://developer.android.com/reference/android/os/AsyncTask
class SyncTaskCounter extends AsyncTask<Void, Double, Void> {
@Override
protected Void doInBackground(Void... voids) {
double price = 0;
while (!isCancelled()) {
price = price + 0.05;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(price); // this instructs to call onProgressUpdate from UI thread.
}
return null;
}
@Override
protected void onProgressUpdate(Double... price) {
printPrice(price[0]); // this is called on UI thread
}
@Override
protected void onCancelled() {
super.onCancelled();
}
}
添加回答
舉報(bào)