ProgressDialog new Activity Asynctask 没有显示,为什么?

ProgressDialog new Activity Asynctask is not showing, why?

我用下面的代码做了一个 AsyncTaskclass

public class removeDialog extends AsyncTask<Void, Void, Void> {

Context c;
ProgressDialog asyncDialog;
String page;

public removeDialog(Context c, String page) {
    this.c = c;
    this.page = page;

    asyncDialog = new ProgressDialog(c);
}

@Override
protected void onPreExecute() {
    //set message of the dialog
    asyncDialog.setTitle("Please wait");
    asyncDialog.setMessage("Loading...");
    asyncDialog.setCancelable(false);
    //show dialog
    asyncDialog.show();

    if (page == "algemeneVoorwaarden") {
        Intent intent = new Intent(c, algemeneVoorwaarden.class);
        c.startActivity(intent);
    }
    if (page == "contact") {
        Intent intent = new Intent(c, contactTest.class);
        c.startActivity(intent);
    }

    super.onPreExecute();
}

@Override
protected Void doInBackground(Void... arg0) {

    //don't touch dialog here it'll break the application
    //do some lengthy stuff like calling login webservice

    return null;
}

@Override
protected void onPostExecute(Void result) {
    //hide the dialog
    asyncDialog.dismiss();

    super.onPostExecute(result);
}
}

我第一次尝试: 第一次我看到 ProgressDialog,但第二次我想打开 activity 我什么也没看到。

我第二次尝试: 即使是第一次尝试,我也没有得到 ProgressDialog。

我在 AsyncTask class 中执行我的代码,代码:

voorwaarden.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new removeDialog(c, "algemeneVoorwaarden").execute();
            }
        });

有人知道为什么它不起作用吗?请帮助我。

您的对话框将在显示后立即关闭,因为您的 doInBackground 是空的。尝试添加一个 Thread.sleep() 几秒钟,只是为了模拟延迟。

此外,我怀疑您开始的新活动会留下您的对话。因此,我建议您暂时在没有这些新活动的情况下测试代码。

public class RemoveDialog extends AsyncTask<Void, Void, Void> {

    ProgressDialog asyncDialog;

    public RemoveDialog(Context c) {
        asyncDialog = new ProgressDialog(c);
    }

    @Override
    protected void onPreExecute() {
        //set message of the dialog
        asyncDialog.setTitle("Please wait");
        asyncDialog.setMessage("Loading...");
        asyncDialog.setCancelable(false);

        //show dialog
        asyncDialog.show();

        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0) {

        try {
            Thread.sleep(3000);
        }
        catch (InterruptedException ex) {
            ex.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        //hide the dialog
        asyncDialog.dismiss();

        super.onPostExecute(result);
    }
}