请考虑以下代码:
package com.reallybelievebig.asynctaskextracredit;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class AsyncTaskTestActivity extends AppCompatActivity {
private static final String TAG = AsyncTaskTestActivity.class.getSimpleName();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_task_test);
new TestTask().execute("Execute");
Log.d(TAG, "In UI Thread!");
}
private class TestTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
for (int i = 0; i <= 100; i+=20) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Log.e(TAG, "Exception Caught: ", e);
}
publishProgress(i);
}
return "Background Task Complete";
}
@Override
protected void onProgressUpdate(Integer... values) {
Toast.makeText(AsyncTaskTestActivity.this, "Progress: " + values[0], Toast.LENGTH_LONG).show();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d(TAG, "In onPostExecute: " + s);
Toast.makeText(AsyncTaskTestActivity.this, s, Toast.LENGTH_LONG).show();
}
}
}
我正在使用TestTask.execute()
方法从主UI线程启动异步任务。
doInBackground()
方法运行正常。它会休眠一段时间,调用publishProgress()
方法并以onProgressUpdate()
方法显示Toast。
我希望只有在onPostExecute()
完成后才能调用doInBackground()
方法。但是,只要我启动应用程序,就会以onPostExecute()
方法获取日志消息。
有些问题我无法弄明白。这段代码有什么问题?