首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Android做后台工作时,如何使用AsyncTask显示ProgressDialog?

在Android做后台工作时,如何使用AsyncTask显示ProgressDialog?
EN

Stack Overflow用户
提问于 2010-10-09 03:18:46
回答 2查看 74.1K关注 0票数 21

可能重复:

Updating progress dialog in Activity from AsyncTask

我正在开发我的第一个Android应用程序,我需要一个ProgressDialog来显示,而后台任务,在这种情况下,只是一个服务器上的http调用,发生。我在这方面做了一些研究,也已经检查了与这个主题相关的其他帖子。

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

Android show ProgressDialog until activity UI finished loading

Android SplashScreen

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

在其他方面。

然后我写了一些代码:

1)在我的活动中,我声明了一个ProgressDialog类型的变量

public class LoginActivity extends Activity {

    public static final String TAG = "LoginActivity";

    protected ProgressDialog progressDialog; 
...

2)我还写了一个内部类来根据需要扩展AsyncTask,在这里的doInBackGround中,我调用了一个静态方法,它实际执行对服务器的POST http请求,在服务器端,我已经阻止了服务器响应20s来验证进度对话框。

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)当按钮被按下时,I然后构建ProgressDialog anc调用我创建的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秒)内进度显示并调用下一个活动。

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

提前谢谢你。

嗨,由查理辛建议(?)在这个线程的第一个答案中,我尝试修改了我的代码,现在它是这样的(不幸的是,到目前为止它并没有像预期的那样工作):

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

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-10-09 03:26:35

将您的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);
票数 29
EN

Stack Overflow用户

发布于 2010-10-09 05:13:36

最终的解决方案是将从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();
        }
    }; 

所有工作都发生在EfetuaLogin AsyncTask实现中:

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来传递参数给你的任务。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3893626

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档