无法从AsynkTask中显示ProgressDialog

时间:2016-09-14 11:22:54

标签: java android android-asynctask

我正在尝试从AsyncTask显示ProgressDialog但是没有显示...如果我删除了PostExecute的'dialog.dismiss()',这个任务就像'post()',它显示了对话结束时的对话。我对此感到疯狂!

private static class Experimento extends AsyncTask<String, Void, String> 
{   
    ProgressDialog dialog;

    @Override
    protected void onPreExecute() 
    {
        super.onPreExecute();

        dialog = new ProgressDialog(Config.getCurrent_Context());
        dialog.setMessage("Cargando...");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
    }

    protected String doInBackground(String... params) 
    {   
        try
        {     
            Config.getCurrent_Context().runOnUiThread(new Runnable()
            {   
                @Override
                public void run()
                {
                    try
                    {
                        //Work, work, work...
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            });
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

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

        dialog.dismiss();
    }
}

现在尝试在构造函数中提供Activity但仍无效...

private static ProgressDialog dialog;

    public Experimento(Activity act)
    {
        Log.w("Experimento", "Experimento");
        dialog = new ProgressDialog(act);
        dialog.setMessage("Cargando...");
        dialog.setCancelable(false);
        dialog.show();
    }

    @Override
    protected void onPreExecute() 
    {
        super.onPreExecute();
    }

2 个答案:

答案 0 :(得分:0)

你应该删除setIntermidiate(true);

答案 1 :(得分:0)

试试这个,它对我有用:

  Override
    protected void onPreExecute() 
    {

        dialog = new ProgressDialog(Config.getCurrent_Context());
        dialog.setMessage("Cargando...");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
    }

    protected String doInBackground(String... params) 
    {   
  String result = " ";
        try
        {     
            Config.getCurrent_Context().runOnUiThread(new Runnable()
            {   
                @Override
                public void run()
                {
                    try
                    {
                        //Work, work, work...
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            });
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return result;
    }

    protected void onPostExecute(String result) 
    {

        dialog.dismiss();
    }