1 回答

TA贡献1797条经验 获得超4个赞
在 Android 上,您必须在 UI 线程上运行所有 UI 代码。AsyncTask 中的代码在其他线程中执行,因此它不能调用 UI 方法。
为此,您应该使用 Handler(代码将在 UI 线程中调用): 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,那么你应该从方法更新 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();
}
}
添加回答
举报