繁体   English   中英

如何防止Android应用程序因后台线程中的IOException而崩溃?

[英]How to prevent android app from crashing due to IOException in background thread?

我想知道是否有一种方法可以防止尝试在传递的uri字符串上建立连接的后台线程因IOExceptionMalformedURLException而导致整个应用程序崩溃。 虽然我捕获了抛出的所有异常并将消息打印到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());

    }
}
}

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

谢谢。

然后把它放在捕获部分

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);
                }
            }

我建议你在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.
}

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM