我正在使用ASyncTask
在我的應用程序中執行簡單的動畫。但它只適用於Android 5.0+,低於它只是崩潰,並說我從錯誤的線程編輯UI。這裏是我的代碼:Android ASyncTask在Android 4及以下崩潰
private class AlphaCorrect extends AsyncTask<Integer, Integer, Integer> {
float alpha;
@Override
protected Integer doInBackground(Integer[] params) {
Log.i("back","running");
for (float i = 0.0f; i < 0.9; i += 0.02) {
alpha = i;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Update();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (float i = 0.8f; i > -0.1f; i -= 0.02) {
alpha = i;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Update();
}
return null;
}
@Override
protected void onPreExecute() {
Log.i("run", "RUN");
canClick = false;
}
@Override
protected void onPostExecute(Integer result) {
canClick = true;
}
protected void Update() {
correct.setAlpha(alpha);
}
}
我試過Runnable
,Thread
和其他一些東西了。有任何想法嗎?
logcat好嗎?顯示確切的錯誤信息。 –
我想知道它在Android 5.0+上的工作原理。您確實不允許使用除main之外的任何線程對UI執行任何操作。每當你需要更新UI時,只需在*主線程*上發佈一個Runnable(如果系統沒有爲你提供回調)。 – frangulyan