【问题标题】:How to prevent android app from crashing due to IOException in background thread?如何防止android应用程序由于后台线程中的IOException而崩溃?
【发布时间】:2013-09-28 19:01:14
【问题描述】:

我想知道是否有一种方法可以防止由于IOExceptionMalformedURLException 而导致试图在传递的uri 字符串上建立连接的后台线程使整个应用程序崩溃。 虽然我捕获了所有抛出的异常并将消息打印到 logcat,但我不希望应用程序与 msg 一起崩溃:Unfortunately, MyApp has stopped。 我希望应用程序通过在主/UI 线程上发布相关的错误消息来优雅地退出。

比如说:

public void onClick(View v){
    new Thread(new MyDownloaderClass(url_str)).start();
}

private class MyDownloaderClass implements Runnable{
    private String url_str;
    public MyDownloaderClass(String arg){url_str=arg;}
    public void run(){
        URL url=null;
    int respCode=0;
    try{
        url=new URL(str);
        HttpURLConnection connection=(HttpURLConnection)url.openConnection();
        connection.setRequestMethod("HEAD");
        connection.connect();
        respCode=connection.getResponseCode();

    }catch(MalformedURLException e){
        Log.e(TAG,e.getClass()+": "+e.getMessage());

    }catch(IOException e){
        Log.e(TAG,e.getClass()+": "+e.getMessage());

    }
}
}

在这种情况下,如果输入的字符串不是可行的 url 或无法建立连接,我的应用程序就会崩溃。但我希望能够在 UI 线程上发布一些有用的消息并防止应用程序崩溃。

谢谢。

【问题讨论】:

  • Logcat 中的错误跟踪显示什么?
  • 因此,如果用户输入一些乱码 url 并单击按钮,那么我会得到 09-28 15:05:29.262: E/MyApp Activity(2940): class java.net.MalformedURLException: Protocol not发现:然后应用程序崩溃。我想以一种要求用户通过在主线程上发布消息来检查输入的 url 的方式来处理这个问题。

标签: android multithreading


【解决方案1】:

然后放到catch部分

catch (Exception e) {
     if(e.getMessage().toString().equalsIgnoreCase("write your exception from logcat"))
        {
         //show your error in a toast or a dialog
         Toast.makeText(this," your pertinent error message ", Toast.LENGTH_LONG);
                }
            }

【讨论】:

  • 嗨 manishika,我厌倦了这样做。由于它是一个后台线程,我使用 runOnUiThread 方法在主线程上创建一个 toast,以通知用户输入错误。但是应用程序只是在捕获异常时崩溃,并且不会在 UI 上创建 toast
【解决方案2】:

我建议您在 AsyncTask 中执行所有网络操作。

在 AsyncTask 方法的 doinBackground() 中,使用 try/catch 执行所有网络操作。如下处理异常。

//Define "Exception error = null;" in your AsyncTask class.
catch(Exception ex) {
    Log.e(TAG,e.getClass()+": "+ex.getMessage());
    error = ex;
}

在 onPostExecute() 方法中检查

if (error ! = null) {
    //Toast msg . // You should not call a Toast msg in your doinBackground method.
}

【讨论】:

  • 嗨,pushkar,感谢您的回复。我想知道如何在不使用异步任务的情况下完成。
【解决方案3】:

你错误地使用了 Thread.start() 而不是 Thread.run():

          new Thread(new MyDownloaderClass(url_str)).start();

您的代码仍然在原始线程上运行,因此出现异常会导致崩溃。

【讨论】:

    猜你喜欢
    • 2014-05-23
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2011-04-20
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多