我想在我的 Asynctask 中运行代码时显示一个不确定的进度条,但是(如果我是对的(因为我在 MainActivity 中使用 .get(( 函数,UI 线程冻结,直到 AsyncTask 给出响应,因此进度条不会显示。如何使进度条在 UI 线程等待异步任务完成并返回一些值时出现在屏幕上?
主活动
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
public void showSpinner(View view){
CustomAsyncTask customAsyncTask = new CustomAsyncTask(this);
customAsyncTask.setProgressBar(progressBar);
try {
String message = customAsyncTask.execute().get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Toast.makeText(this,
"Time is up", Toast.LENGTH_LONG).show();
}}
异步任务
public class CustomAsyncTask extends android.os.AsyncTask<Void, Void, String> {
Context context;
CustomAsyncTask(Context ctx) {
context = ctx;
}
ProgressBar progressBar;
public void setProgressBar(ProgressBar progressBar) {
this.progressBar = progressBar;
}
@Override
protected String doInBackground(Void... voids) {
SystemClock.sleep(2000);
String message = "hello world";
return message;
}
@Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected void onPostExecute(String message) {
progressBar.setVisibility(View.GONE);
}}
尝试在没有.get()
的情况下运行AsyncTask
。
您可以使用界面(见原始答案(:
您的界面:
public interface OnTaskCompleted{
void onTaskCompleted();
}
您的活动:
public MainActivity extends AppCompatActivity implements OnTaskCompleted{
//your MainActivity
}
和你的异步任务:
public class CustomAsyncTask extends android.os.AsyncTask<Void, Void, String> {
private OnTaskCompleted listener;
public CustomAsyncTask(OnTaskCompleted listener){
this.listener=listener;
}
//required methods
protected void onPostExecute(Object o){
//your stuff
listener.onTaskCompleted();
}
}
另一种方法是在MainActivity
中添加message
的二传手:
public class MainActivity extends AppCompatActivity {
//...
private String message;
public void setMessage(String message) {
this.message = message;
}
// ...
customAsyncTask.execute();
然后只需在CustomAsyncTask
中更新.onPostExecute()
中的message
:
public class CustomAsyncTask extends android.os.AsyncTask<Void, Void, String> {
//...
@Override
protected void onPostExecute(String message) {
progressBar.setVisibility(View.GONE);
MainActivity activity = (MainActivity) context;
activity.setMessage(message);
}