如何在Android中使用AsyncTask来显示ProgressDialog并执行后台任务?

21

可能是重复的问题:
从AsyncTask更新Activity中的进度对话框

我正在开发我的第一个Android应用程序,需要在后台任务(在这种情况下只是服务器上的http调用)进行时显示ProgressDialog。 我已经对此进行了一些研究,并且已经检查了其他与此主题相关的线程。

http://developer.android.com/reference/android/os/AsyncTask.html

Android显示ProgressDialog直到活动UI加载完成

Android启动画面

http://android-developers.blogspot.com/2009/05/painless-threading.html

除此之外。

接着我需要写一些代码:

1)在我的Activity中,我声明了一个类型为ProgressDialog的变量。

public class LoginActivity extends Activity {

    public static final String TAG = "LoginActivity";

    protected ProgressDialog progressDialog; 
...

2) 我还编写了一个内部类来扩展AsyncTask,其中doInBackground是我调用静态方法的地方,该静态方法实际上执行POST http请求到服务器,在服务器端,我阻塞了服务器响应20秒钟以验证进度对话框。

class EfetuaLogin extends AsyncTask<Object, Void, String> {

        private final static String TAG = "LoginActivity.EfetuaLogin";

        @Override
        protected void onPreExecute()
        {
            Log.d(TAG, "Executando onPreExecute de EfetuaLogin");
        }


        @SuppressWarnings("unchecked")
        @Override
        protected String doInBackground(Object... parametros) {
            Log.d(TAG, "Executando doInBackground de EfetuaLogin");
            Object[] params = parametros;
            HttpClient httpClient = (HttpClient) params[0];
            List<NameValuePair> listaParametros = (List<NameValuePair>) params[1];
            String result = null;
            try{
            result = HttpProxy.httpPost(AnototudoMetadata.URL_AUTENTICACAO, httpClient, listaParametros);
            }catch (IOException e) {
                Log.e(TAG, "IOException, Sem conectividade com o servidor do Anototudo! " + e.getMessage());
                e.printStackTrace();
                return result;
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result)
        {
            progressDialog.dismiss();
        }

    } 

3) 当按钮被按下时,我会构建ProgressDialog并调用我创建的AsyncTask:

    OnClickListener loginListener = new OnClickListener() {
      public void onClick(View v) {


//next line should start progress dialog in main thread ?????
   progressDialog = ProgressDialog.show(LoginActivity.this, "Login in", "Wait a moment please", true, false);

   //next couple of lines should do an ascyn call to server
   EfetuaLogin efetuaLogin = new EfetuaLogin();
   efetuaLogin.execute(params);
   try {
    //recover the server response and sets time out to be 25seconds
    sResposta = efetuaLogin.get(25, TimeUnit.SECONDS);

好的,我相信这应该展示一个进度对话框,而AsyncTask会在后台查询服务器,但我得到的是没有进度条,直到服务器响应到达,然后在短暂时间内(不到1秒)显示进度,接下来调用下一个Activity。

正如我所提到的,我已经重新检查了这段代码,但只是找不到我错在哪里。 有什么建议吗?

提前致谢。

嗨,正如Charlie Sheen(???)在这个线程的第一个答案中建议的那样,我尝试改变了我的一些代码,现在它是这样的(不幸的是,目前它并没有像预期的那样工作):

OnClickListener loginListener = new OnClickListener() {
        public void onClick(View v) {
                //async call????????
        new EfetuaLogin().execute(params);
...

然后在AsyncTask中处理响应的所有工作:

class EfetuaLogin extends AsyncTask<Object, Void, String> {

        private final static String TAG = "LoginActivity.EfetuaLogin";

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            Log.d(TAG, "Executando onPreExecute de EfetuaLogin");
            //inicia diálogo de progresso, mostranto processamento com servidor.
            progressDialog = ProgressDialog.show(LoginActivity.this, "Autenticando", "Contactando o servidor, por favor, aguarde alguns instantes.", true, false);
        }


        @SuppressWarnings("unchecked")
        @Override
        protected String doInBackground(Object... parametros) {
            Log.d(TAG, "Executando doInBackground de EfetuaLogin");
            Object[] params = parametros;
            HttpClient httpClient = (HttpClient) params[0];
            List<NameValuePair> listaParametros = (List<NameValuePair>) params[1];
            String result = null;
            try{
            result = HttpProxy.httpPost(AnototudoMetadata.URL_AUTENTICACAO, httpClient, listaParametros);
            }catch (IOException e) {
                Log.e(TAG, "IOException, Sem conectividade com o servidor do Anototudo! " + e.getMessage());
                e.printStackTrace();
                return result;
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);

            if (result == null || result.equals("")) {
                progressDialog.dismiss();
                Alerta
                        .popupAlertaComBotaoOK(
                                "Dados incorretos",
                                "Os dados informados não foram encontrados no Sistema! Informe novamente ou cadastre-se antes pela internet.",
                                LoginActivity.this);
                return;
            }

            Log.d(TAG, "Login passou persistindo info de login local no device");
            ContentValues contentValues = new ContentValues();
            contentValues.put(AnototudoMetadata.LOGIN_EMAIL, sLogin);
            contentValues.put(AnototudoMetadata.LOGIN_SENHA, sSenha);
            contentValues.put(AnototudoMetadata.LOGIN_SENHA_GERADA, result);
            LoginDB loginDB = new LoginDB();
            loginDB.addLogin(LoginActivity.this, contentValues);
            Log.d(TAG, "Persistiu info de login no device, redirecionando para menu principal do Anototudo");
            Log.d(TAG, "O retorno da chamada foi ==>> " + result);
            // tudo ok chama menu principal
            Log.d(TAG, "Device foi corretametne autenticado, chamando tela do menu principal do Anototudo.");

            String actionName = "br.com.anototudo.intent.action.MainMenuView";
            Intent intent = new Intent(actionName);
            LoginActivity.this.startActivity(intent);
            progressDialog.dismiss();
        }

    } 

完整的OnClickListener:

OnClickListener loginListener = new OnClickListener() {
    public void onClick(View v) {
        Log.d(TAG, "Usuario logado, chamando menu principal");
        TextView tLogin = (TextView) findViewById(R.id.loginText);
        TextView tSenha = (TextView) findViewById(R.id.senhaText);
        String sLogin = tLogin.getText().toString();
        String sSenha = tSenha.getText().toString();

        if (sLogin.equals("") | sSenha.equals("")) {
            Alerta.popupAlertaComBotaoOK("Campos Obrigatórios",
                    "Os campos Login e Senha são obrigatórios para autenticação do Anototudo.", LoginActivity.this);
            return;
        } else {
            Pattern regEx = Pattern.compile(".+@.+\\.[a-z]+");
            Matcher matcher = regEx.matcher(sLogin);
            if (!matcher.matches()) {
                Alerta.popupAlertaComBotaoOK("Formato e-mail inválido", "O formato do campo e-mail está inválido",
                        LoginActivity.this);
                return;
            }
        }


        List<NameValuePair> listaParametros = new ArrayList<NameValuePair>();
        listaParametros.add(new BasicNameValuePair("login", sLogin));
        listaParametros.add(new BasicNameValuePair("senha", sSenha));

        Log.d(TAG, "valores recuperados dos campos de login e senha: " + sLogin + " | " + sSenha);

        // Reutiliza cliente HttpClient disponibilizado pela Aplicação.
        AnototudoApp atapp = (AnototudoApp) LoginActivity.this.getApplication();
        HttpClient httpClient = atapp.getHttpClient();

        //prepara lista de parametros para fazer chamada asíncrona no servidor para autenticar.
        Object[] params = new Object[2];
        params[0] = httpClient;
        params[1] = listaParametros;

        //faz chamada assincrona
        new EfetuaLogin().execute(params);
    }
};
2个回答

29

将您的ProgressDialog放在onPreExecute中,下面是示例代码:

private ProgressDialog pdia;

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

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

在您的onClickListener中,只需将此行代码放入其中:

new EfetuaLogin().execute(null, null , null);

1
@Marcos Maia:把你所有必要的东西放到doInBackground中。来自doInBackground的输出结果传递到onPostExecute参数,你可以在那里检查服务器响应 - 所有这些都在AsyncTask内部进行。关于你传递到AsyncTask中的值,我无法告诉你任何信息,因为缺少一些代码片段。 - Wroclai
@Marcos Maia:请编辑您的问题。 - Wroclai
@Charlie Sheen:嗨,我已按建议编辑了我的问题 : )。我尝试了你建议的方法,但仍然得到完全相同的行为。参数似乎没问题,因为http调用被正确执行了。问题只在于缺少进度对话框。 - groo
@Marcos Maia:我明白了,但是你能否在onClickListener中发布完整的代码?唯一需要的行是执行AsyncTask类的执行行。不要试图在onClickListener中获取响应。顺便说一下,我看不到您将哪些值发送到AsyncTask参数中。 - Wroclai
@Marcos Maia:所需的代码(除了您的执行)是if/else语句和TextView/String(您可以将其全局化)。从“List...”到“...listaParametros;”可以粘贴到“doInBackground”中,然后您就不需要向AsyncTask发送任何值。您还可以在if语句中添加一个“|”。 - Wroclai
显示剩余6条评论

8
最终解决方案是将所有代码从OnClickListenerdoInBackground方法从AsyncTask实现中取出。现在的代码如下:

OnClickListener

OnClickListener loginListener = new OnClickListener() {
        public void onClick(View v) {
            /* Translation note: Original text: "Executando OnClickListener" */
            Log.d(TAG, "OnClickListener has been called");

            /* Translation note: Original text: "faz chamada assincrona" */
            // Make an asynchronous call
            new EfetuaLogin().execute();
        }
    }; 

所有的工作都发生在 EfetuaLoginAsyncTask 实现中:

class EfetuaLogin extends AsyncTask<Object, Void, String> {

        private final static String TAG = "LoginActivity.EfetuaLogin";

        protected ProgressDialog progressDialog;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            Log.d(TAG, "Executando onPreExecute de EfetuaLogin");
            //inicia diálogo de progresso, mostranto processamento com servidor.
            progressDialog = ProgressDialog.show(LoginActivity.this, "Autenticando", "Contactando o servidor, por favor, aguarde alguns instantes.", true, false);
        }


        @SuppressWarnings("unchecked")
        @Override
        /* Translation note: Original text: "Object... parametros"
        protected String doInBackground(Object... parameters) {
            /* Translation note: Original text: "Executando doInBackground de EfetuaLogin" */
            Log.d(TAG, "Executing doInBackground of EfetuaLogin");
            TextView tLogin = (TextView) findViewById(R.id.loginText);
            TextView tSenha = (TextView) findViewById(R.id.senhaText);
            String sLogin = tLogin.getText().toString();
            String sSenha = tSenha.getText().toString();

            if (sLogin.equals("") | sSenha.equals("")) {
                /*
                  Translation notes:
                  1) "Campos Obrigatórios" -> "Required fields"
                  2) "Os campos Login e Senha são obrigatórios para autenticação do Anototudo." -> "Login and Password fields are required for Anototudo authentication."
                Alerta.popupAlertaComBotaoOK("Required fields", "Login and Password fields are required for Anototudo authentication.", LoginActivity.this);
                progressDialog.dismiss();
                return null;
            } else {
                Pattern regEx = Pattern.compile(".+@.+\\.[a-z]+");
                Matcher matcher = regEx.matcher(sLogin);
                if (!matcher.matches()) {
                    /*
                      Translation notes:
                      1) "Formato e-mail inválido" -> "Invalid email format"
                      2) "O formato do campo e-mail está inválido" -> "The email field has an invalid format"
                    */
                    Alerta.popupAlertaComBotaoOK("Invalid email format", "The email field has an invalid format",
                            LoginActivity.this);
                    progressDialog.dismiss();
                    return null;
                }
            }


            List<NameValuePair> listaParametros = new ArrayList<NameValuePair>();
            listaParametros.add(new BasicNameValuePair("login", sLogin));
            listaParametros.add(new BasicNameValuePair("senha", sSenha));
            /* Translation note: Original text: "valores recuperados dos campos de login e senha: " */
            Log.d(TAG, "values retrieved from login and password fields:" + sLogin + " | " + sSenha);

            /* Translation note: Original text: "Reutiliza cliente HttpClient disponibilizado pela Aplicação." */
            // Reuses `HttpClient` made available by the Application.
            AnototudoApp atapp = (AnototudoApp) LoginActivity.this.getApplication();
            HttpClient httpClient = atapp.getHttpClient();

            String result = null;
            try {
                result = HttpProxy.httpPost(AnototudoMetadata.URL_AUTENTICACAO, httpClient, listaParametros);
            } catch (IOException e) {
                Log.e(TAG, "IOException, Sem conectividade com o servidor do Anototudo! " + e.getMessage());
                e.printStackTrace();
                return result;
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);

            if (result == null || result.equals("")) {
                progressDialog.dismiss();
                /*
                  Translation notes:
                  1) "Dados incorretos" -> "Incorrect data"
                  2) "Os dados informados não foram encontrados no Sistema! Informe novamente ou cadastre-se antes pela internet." -> "The reported data was not found in the System! Please report again or sign up on the internet first."
                */
                Alerta.popupAlertaComBotaoOK(
                                "Incorrect data",
                                "The reported data was not found in the System! Please report again or sign up on the internet first.",
                                LoginActivity.this);
                return;
            }
            /* Translation note: Original text: "Login passou persistindo info de login local no device" */
            Log.d(TAG, "Login passed persisting local login info on device");
            ContentValues contentValues = new ContentValues();
            contentValues.put(AnototudoMetadata.LOGIN_EMAIL, sLogin);
            contentValues.put(AnototudoMetadata.LOGIN_SENHA, sSenha);
            contentValues.put(AnototudoMetadata.LOGIN_SENHA_GERADA, result);
            LoginDB loginDB = new LoginDB();
            loginDB.addLogin(LoginActivity.this, contentValues);
            /* Translation note: Original text: "Persistiu info de login no device, redirecionando para menu principal do Anototudo" */
            Log.d(TAG, "Persisting login info on device, redirecting to Anototudo main menu");
            /* Translation note: Original text: "O retorno da chamada foi ==>> " */
            Log.d(TAG, "The callback was ==>>" + result);
            /* Translation note: Original text: "tudo ok chama menu principal" */
            // everything ok call main menu
            /* Translation note: Original text: "Device foi corretametne autenticado, chamando tela do menu principal do Anototudo." */
            Log.d(TAG, "Device has been correctly authenticated by calling the main menu screen of Annotate.");

            String actionName = "br.com.anototudo.intent.action.MainMenuView";
            Intent intent = new Intent(actionName);
            LoginActivity.this.startActivity(intent);
            progressDialog.dismiss();
        }

    }

现在它按预期工作,但我必须说我有点困惑,因为 AsyncTask 文档说你可以使用 execute 来传递参数给你的任务。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接