如何处理doInbackGround异常?

时间:2014-05-29 05:02:01

标签: android android-asynctask

我有一个下载图像的asyncTask。有时它无法下载并提供此异常java.lang.RuntimeException: An error occurred while executing doInBackground()

现在我想要处理这个问题,当它发生时会停止下载(因为我在onPreExecute中创建了一个显示下载进度的通知栏)并向Toast发送了一条未完成下载的消息!

@Override
protected Void doInBackground(Void... unused) {
    @Override
    protected void onPreExecute() {
    mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);   //.... to create a notification 
    }
 downloadPackage(IMG_DIR_URL);//my function to download an imagedo some stuff
 return null;
}
protected void onProgressUpdate(Integer... progress) {
    // setting progress bar on notification area
    //fore example mBuilder.setProgress(100, progress[0], false);
}

2 个答案:

答案 0 :(得分:1)

在你的情况类似的情况下,我选择了以下方法:

   private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     Exception exception = null; 
        protected Long doInBackground(URL... urls) {
            try{
               //downloading code here..
             }catch(SomeException e){
              exception = e;
             }
             return totalSize;
         }


         protected void onPostExecute(Long result) {
             if(exception!=null){
               // show toast.
               // cancel async task. (this.cancel())

             }else{
               // no exception while downloading, check for result and take corresponding action on result
             }
         }

 }

答案 1 :(得分:0)

只需将您的代码放在try / catch块中,在catch块中就可以处理异常,应用程序永远不会崩溃:使用下面的代码来处理并获取错误,它会为您提供methid和class name以及行号例外。

try {
        //do your stuff
    } catch (Exception e) {
        for (int i = 0; i < e.getStackTrace().length; i++) {
            StackTraceElement oStackTace = e.getStackTrace()[i];
            String ClassName = oStackTace.getClassName();
            String MethodName = oStackTace.getMethodName();
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String exceptionAsString = sw.toString();
            Log.d("Class Name: " + ClassName + " Method Name: "
                    + MethodName, exceptionAsString);
    }
    }