簡體   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