Android - AsyncTask - onPreExecute()在doInBackground()完成后运行

Dem*_*Wav 1 android android-asynctask

我试图在onPreExecute()中启动ProgressDialog时出现AsyncTask,做一些事情doInBackground(),并关闭ProgressDialogin onPostExecute().

在任何地方,我认为这应该是简单而直接的,但我必须做错事.

每当我点击Button我的应用程序进行更新并AsyncTask运行应用程序冻结,等待一点,然后ProgressDialog立即出现并消失,工作doInBackground()完成.我不明白为什么onPreExecute()会被追赶doInBackground(),但这似乎正是这里发生的事情.这是代码:

public class UpdateStats extends AsyncTask<CatchAPI, Void, String[]> {

    private ProgressDialog pdia;
    private Context context;
    private APIParser parser = new APIParser();

    public UpdateStats(Context contexts) {
        context = contexts;
    }

    @Override
    protected void onPreExecute() {
        pdia = new ProgressDialog(context);
        pdia.setMessage("Loading...");
        pdia.show();
        super.onPreExecute();
    }

    @Override
    protected String[] doInBackground(CatchAPI... api) {

        String apiOutput = api[0].returnAPI();

        return new String[] {
                parser.getPoolName(apiOutput), 
                parser.getHashRate(apiOutput), 
                parser.getWorkers(apiOutput), 
                parser.getSharesThisRound(apiOutput)
            };
    }

    @Override
    protected void onPostExecute(String[] result) {
        pdia.dismiss();
        super.onPostExecute(result);
    }

}
Run Code Online (Sandbox Code Playgroud)

和MainActivity中的onClickListener:

updateButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        String[] text = null;
        UpdateStats updater = new UpdateStats(context);
        try {
            text = updater.execute(api).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        poolNameTV.setText(text[0]);
        hashRateTV.setText(text[1]);
        workersTV.setText(text[2]);
        sharesThisRoundTV.setText(text[3]);
    }
});
Run Code Online (Sandbox Code Playgroud)

ρяσ*_*я K 7

在这里 :

text = updater.execute(api).get();  //<<<
Run Code Online (Sandbox Code Playgroud)

您正在调用AsyncTask.get(),它会冻结UI线程执行,直到doInBackground执行未完成.执行AsyncTask为:

updater.execute(api)
Run Code Online (Sandbox Code Playgroud)

onPostExecutedoInBackground执行完成时更新在UI Thread上调用的UI元素.

@Override
protected void onPostExecute(String[] result) {
    pdia.dismiss();
    // update UI here..
    poolNameTV.setText(result[0]);
    hashRateTV.setText(result[1]);
    workersTV.setText(result[2]);
    sharesThisRoundTV.setText(result[3]);

    super.onPostExecute(result);

}
Run Code Online (Sandbox Code Playgroud)