在AsyncTask中关闭进度对话框并处理异常

时间:2014-04-23 05:02:06

标签: android android-asynctask progressdialog

如果在我的AsyncTask中doInBackground发生任何异常,我将无法解除进度对话,因为它永远不会到达onPostExecute,并且永远不会关闭进行ANR的进度对话框。

以下是AsyncTask的代码

   private class checkAS extends AsyncTask<Void, Void, Void>
{
    ProgressDialog dialogue;
    @Override
    protected void onPostExecute() {
        // TODO Auto-generated method stub
        super.onPostExecute();
        dialogue.dismiss(); 

    }
    @Override
    protected Void doInBackground(Void... params) {
        //Long Network Task
        return null;
    }
    @Override
    protected void onPreExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPreExecute(result);
        dialogue = new ProgressDialog(MainActivity.this);
        dialogue.setTitle("Processing");
        dialogue.setMessage("Getting Profile Information");
        dialogue.setIndeterminate(true);
        dialogue.setCancelable(false);
        dialogue.show();
    }
}

我的问题是,如果在doInBackground发生任何异常,我将如何处理它以及如何调用onPostExecute来解除对话?我不能在doInBackground上解雇它。如何同步?

7 个答案:

答案 0 :(得分:1)

试试这个..

doInBackground返回类似字符串的内容。如果Exceptioncatch分配字符串值error,否则返回success

private class checkAS extends AsyncTask<Void, Void, String>
{
    ProgressDialog dialogue;
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        dialogue = new ProgressDialog(MainActivity.this);
        dialogue.setTitle("Processing");
        dialogue.setMessage("Getting Profile Information");
        dialogue.setIndeterminate(true);
        dialogue.setCancelable(false);
        dialogue.show();

    }
    @Override
    protected String doInBackground(Void... params) {
        //Long Network Task
        String result;
        try{
          result = "success"
        }
        catch(Exception e){
          result = "error";
        }
        return result;
    }
    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);  
        if(result.equals("error"))          
           dialogue.dismiss(); 
        else
           // do something
    }
}

答案 1 :(得分:0)

您正在onPostExecute方法中创建对话框对话框,它应该在onPreExecute方法中。 试试这个。

     private class checkAS extends AsyncTask<Void, Void, Void>
    {
        ProgressDialog dialogue;
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

 dialogue = new ProgressDialog(MainActivity.this);
            dialogue.setTitle("Processing");
            dialogue.setMessage("Getting Profile Information");
            dialogue.setIndeterminate(true);
            dialogue.setCancelable(false);
            dialogue.show();

        }
        @Override
        protected Void doInBackground(Void... params) {
            //Long Network Task
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
 dialogue.dismiss(); 

        }
    }

答案 2 :(得分:0)

@Override
    protected String doInBackground(String... params)
    {
        System.out.println("check user profile");
        try
        {

        }
        catch (Exception e)
        {
            e.printStackTrace();
            publishProgress((e.getMessage()));
        }
        return result;

    }

    @Override
    protected void onProgressUpdate(String... values)
    {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
        Toast.makeText(activity, values[0], Toast.LENGTH_LONG);

            if(dialog != null && dialog.isShowing())
                dialog.dismiss();

    }

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

            if(dialog != null && dialog.isShowing())
            {
                dialog.dismiss();
            }
       }

答案 3 :(得分:0)

您可能希望忽略finally构建的try catch块中的对话框。

try {
...
} catch {
...
finally{
//dismiss dialog here.
}

答案 4 :(得分:0)

首先使用您可以检查的代码检查对话框是否显示

 if(dialog.isShowing())
 dialog.dismiss();

并使用异常处理来避免未知的异常

答案 5 :(得分:0)

    private class checkAS extends AsyncTask<String, Integer, String> {

                   public static final int POST_TASK = 1;

                   private static final String TAG = "checkAS";

                   // connection timeout, in milliseconds (waiting to connect)
                   private static final int CONN_TIMEOUT = 12000;

                   // socket timeout, in milliseconds (waiting for data)
                   private static final int SOCKET_TIMEOUT = 12000;

                   private int taskType = POST_TASK;
                   private Context mContext = null;
                   private String processMessage = "Processing...";

                   private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

                   private ProgressDialog pDlg = null;

                   public checkAS(int taskType, Context mContext, String processMessage) {

                       this.taskType = taskType;
                       this.mContext = mContext;
                       this.processMessage = processMessage;
                   }

                   public void addNameValuePair(String name, String value) {

                       params.add(new BasicNameValuePair(name, value));
                   }
                   @SuppressWarnings("deprecation")
                private void showProgressDialog() {

                       pDlg = new ProgressDialog(mContext);
                       pDlg.setMessage(processMessage);
                       pDlg.setProgressDrawable(mContext.getWallpaper());
                       pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                       pDlg.setCancelable(false);
                       pDlg.show();

                   }

                   @Override
                   protected void onPreExecute() {

                       showProgressDialog();

                   }

                   protected String doInBackground(String... urls) {

                       String url = urls[0];
                       String result = "";

                       HttpResponse response = doResponse(url);

                       if (response == null) {
                           return result;
                       } else {

                           try {

                               result = inputStreamToString(response.getEntity().getContent());

                           } catch (IllegalStateException e) {
                               Log.e(TAG, e.getLocalizedMessage(), e);

                           } catch (IOException e) {
                               Log.e(TAG, e.getLocalizedMessage(), e);
                           }

                       }

                       return result;
                   }

                   @Override
                   protected void onPostExecute(String response) {

                       handleResponse(response);
                       pDlg.dismiss();

                   }
private HttpParams getHttpParams() {

            HttpParams htpp = new BasicHttpParams();

            HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
            HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);

            return htpp;
        }

        private HttpResponse doResponse(String url) {

            // Use our connection and data timeouts as parameters for our
            // DefaultHttpClient
            HttpClient httpclient = new DefaultHttpClient(getHttpParams());

            HttpResponse response = null;

            try {
                switch (taskType) {

                case POST_TASK:

                    HttpPost httppost= new HttpPost(url);
                    httppost.setEntity(new UrlEncodedFormEntity(params));
                    response = httpclient.execute(httppost);

                    break;
                }
            } 
            catch (Exception e) {
            //  display("Remote DataBase can not be connected.\nPlease check network connection.");

                Log.e(TAG, e.getLocalizedMessage(), e);
                return null;

            }

            return response;
        }

        private String inputStreamToString(InputStream is) {

            String line = "";
            StringBuilder total = new StringBuilder();

            // Wrap a BufferedReader around the InputStream
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
                // Read response until the end
                while ((line = rd.readLine()) != null) {
                    total.append(line);
                }
            } catch (IOException e) {
                Log.e(TAG, e.getLocalizedMessage(), e);
            }
            catch(Exception e)
            {
                Log.e(TAG, e.getLocalizedMessage(), e);
            }

            // Return full string
            return total.toString();
        }

    }
    public void handleResponse(String response) 

    {    
    //display("Response:"+response);
        if(!response.equalsIgnoreCase(""))
        {
            JSONObject jso;
            try {
                //do your stuff
                }
            catch (JSONException e1) {

                Log.e(TAG, e1.getLocalizedMessage(), e1);
            }
            catch(Exception e)
            {
                Log.e(TAG, e.getLocalizedMessage(), e);
            }


        }
        else
        {
            display("Could not able to reach Server!");
        }


    }

答案 6 :(得分:0)

试试这个:

private class checkAS extends AsyncTask<Void, Void, Boolean> {
    ProgressDialog dialogue;

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        dialogue.dismiss();
    }
       @Override
       protected Boolean doInBackground(Void... params) {
           try {
               Thread.sleep(15000);
           } catch (Exception e) {}
           return true;
       }
       @Override
       protected void onPreExecute() {
           super.onPreExecute();
           dialogue = new ProgressDialog(Main.this);
           dialogue.setTitle("Processing");
           dialogue.setMessage("Getting Profile Information");
           dialogue.setIndeterminate(true);
           dialogue.setCancelable(false);
           dialogue.show();
       }
   }