显示带有AsyncTask.execute()。get()的ProgressBar

时间:2018-08-29 22:56:58

标签: android-asynctask android-progressbar

我想在Asynctask中运行代码时显示不确定的ProgressBar,但是(如果我是对的),因为我在MainActivity中使用.get()函数,所以UI线程会冻结,直到AsyncTask给出响应为止因此,ProgressBar将不会显示。如何使UI线程在等待Asynctask完成并返回一些值时在屏幕上显示ProgressBar?

MainActivity

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();
}}

AsyncTask

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);
}}

1 个答案:

答案 0 :(得分:0)

尝试在没有AsyncTask的情况下运行.get()

您可以使用界面(see original answer):

您的界面:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

您的活动:

public MainActivity extends AppCompatActivity implements OnTaskCompleted{
    //your MainActivity
}

还有您的AsyncTask:

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();
    }
}

另一种方法是在message中为MainActivity添加设置器:

public class MainActivity extends AppCompatActivity {
//...
private String message;
public void setMessage(String message) {
    this.message = message;
}
// ...
customAsyncTask.execute();

然后只需更新message.onPostExecute()中的CustomAsyncTask

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);
}