我应该如何处理AsyncTask种类中的异常?

时间:2012-11-10 21:51:24

标签: android asynchronous

我在我的活动中有上面的课程,并从activitie的OnCreate方法运行它。

class UpdateTask extends AsyncTask<String, Void, Void>{
        @Override
        protected Void doInBackground(String... params) {
            Log.d(this.toString(), "-> doInBackground");
            HttpResponse response;
            try {
                HttpParams params1 = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(params1, 3000);
                HttpConnectionParams.setSoTimeout(params1, 5000);
                HttpClient httpclient = new DefaultHttpClient(params1);
                Log.d(this.toString(), "HTTP GET to " + "http://www.google.com");
                response = httpclient.execute(new HttpGet("http://www.google.com"));

                //RequestTask t = new RequestTask();
                //response = t.doIt("http://www.google.com");  
                StatusLine statusLine = response.getStatusLine();

                if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                    ByteArrayOutputStream out = new ByteArrayOutputStream();                    
                    response.getEntity().writeTo(out);
                    out.close();
                    String responseString = out.toString(); 
                    EventItem ei = new EventItem(responseString, responseString, null);
                    addEventItemToContent(ei, ContentStatus.ACTIVE);
                    Log.d(this.toString(), "doInBackground -success->");
                } else {
                    Log.d(this.toString(), "doInBackground -something wrong->");
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "Интернет недоступен", Toast.LENGTH_LONG).show();

            }

LogCat说:

11-11 01:31:19.100: D/com.rkovalev.first.app.MainActivity$UpdateTask@4138ae20(9956): -> doInBackground
11-11 01:31:19.100: D/com.rkovalev.first.app.MainActivity$UpdateTask@4138ae20(9956): HTTP GET to http://www.google.com
11-11 01:31:59.560: W/dalvikvm(9956): threadid=11: thread exiting with uncaught exception (group=0x409961f8)
11-11 01:31:59.580: E/AndroidRuntime(9956): FATAL EXCEPTION: AsyncTask #1
11-11 01:31:59.580: E/AndroidRuntime(9956): java.lang.RuntimeException: An error occured while executing doInBackground()
11-11 01:31:59.580: E/AndroidRuntime(9956):     at android.os.AsyncTask$3.done(AsyncTask.java:278)
11-11 01:31:59.580: E/AndroidRuntime(9956):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-11 01:31:59.580: E/AndroidRuntime(9956):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-11 01:31:59.580: E/AndroidRuntime(9956):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-11 01:31:59.580: E/AndroidRuntime(9956):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-11 01:31:59.580: E/AndroidRuntime(9956):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
11-11 01:31:59.580: E/AndroidRuntime(9956):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-11 01:31:59.580: E/AndroidRuntime(9956):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-11 01:31:59.580: E/AndroidRuntime(9956):     at java.lang.Thread.run(Thread.java:856)
11-11 01:31:59.580: E/AndroidRuntime(9956): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
11-11 01:31:59.580: E/AndroidRuntime(9956):     at android.os.Handler.<init>(Handler.java:121)
11-11 01:31:59.580: E/AndroidRuntime(9956):     at android.widget.Toast$TN.<init>(Toast.java:317)
11-11 01:31:59.580: E/AndroidRuntime(9956):     at android.widget.Toast.<init>(Toast.java:91)
11-11 01:31:59.580: E/AndroidRuntime(9956):     at android.widget.Toast.makeText(Toast.java:233)
11-11 01:31:59.580: E/AndroidRuntime(9956):     at com.rkovalev.first.app.MainActivity$UpdateTask.doInBackground(MainActivity.java:207)
11-11 01:31:59.580: E/AndroidRuntime(9956):     at com.rkovalev.first.app.MainActivity$UpdateTask.doInBackground(MainActivity.java:1)
11-11 01:31:59.580: E/AndroidRuntime(9956):     at android.os.AsyncTask$2.call(AsyncTask.java:264)
11-11 01:31:59.580: E/AndroidRuntime(9956):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-11 01:31:59.580: E/AndroidRuntime(9956):     ... 5 more

我的代码中有错误,或者我应该处理来自其他地方的异常?


UPD:上面代码中的问题:

class UpdateTask extends AsyncTask<String, Integer, Void>{
    @Override
    protected Void doInBackground(String... params) {
    this.onProgressUpdate(0);           
    return null;
    }

    @Override
        protected void onProgressUpdate(Integer... codes) {
    Toast.makeText(getApplicationContext(), 
               "onPr.Upd.: why I haven't access to main ui thread???", Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onPostExecute(Void res) {
    Toast.makeText(getApplicationContext(), 
               "onPost.Ex.: I have access to main thread!", Toast.LENGTH_LONG).show();
    }
}

2 个答案:

答案 0 :(得分:2)

根本问题是你试图在UI线程之外显示一个Toast,在这里:

catch (Exception e) {
    Toast.makeText(getApplicationContext(), "Интернет недоступен", Toast.LENGTH_LONG).show();
}

您无法与其他线程中的UI元素进行交互。

您应该捕获异常(正常处理它),然后调用onPostExecute()以通知Activity有错误,以便Activity可以显示此Toast。

答案 1 :(得分:0)

而不是直接尝试在doInBackground中执行所有UI通知内容,而这些内容本身不是UI线程。

您应该使用有权访问UI线程的方法,例如onProgressUpdate,onPostExecute。 在你的情况下是这样的。

catch (Exception e) {
    publishProgress(error_code); // The error code for identifying
}

并在你的onProgressUpdate方法

 @Override
        protected void onProgressUpdate(Integer... error_codes) {
           if(error_codes[0] == my_desired_error_code){
    Toast.makeText(getApplicationContext(), "Интернет недоступен", Toast.LENGTH_LONG).show();
                }   
        }

基本上,您的流程应该是这样的,以便在UI上进行通知。