0

我的應用程序需要互聯網從我的數據庫中檢索數據。此外,它還使用Google地圖作爲主要活動。我發現,每當我測試它沒有互聯網連接,屏幕變黑,然後它只是崩潰。當我沒有互聯網時,我應該如何在我的代碼中處理這個問題?如何處理我的應用程序沒有互聯網的問題?

回答

1

試試這個.......

public boolean isNet() 
{ 
    boolean status=false; 
    String line; 
    try 
    { 
     URL url = new URL("http://www.google.com"); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); 
     while((line = reader.readLine()) != null) 
     { 
     } 
     status=true; 
    } 
    catch (IOException ex) 
    { 
     System.out.println("ex in isNet : "+ex.toString()); 
     if(ex.toString().equals("java.net.UnknownHostException: www.google.com")) 
      status=false; 
    } 
    catch(Exception e) 
    { 

    } 
    return status; 
} 


if(status==true) 
      { 
      //Do your operation 
      } 
      else 
       show("No Internet Connection."); 
0

您可以檢查互聯網連接:

public boolean isOnline() 
{ 
    //Getting the ConnectivityManager. 
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 

    //Getting NetworkInfo from the Connectivity manager. 
    NetworkInfo netInfo = cm.getActiveNetworkInfo(); 

    //If I received an info and isConnectedOrConnecting return true then there is an Internet connection. 
    if (netInfo != null && netInfo.isConnectedOrConnecting()) 
    { 
     return true; 
    } 
    return false; 
} 

和呈現信息的用戶,如果互聯網連接不可用。

+0

當不存在互聯網我該怎麼辦? – 2013-03-06 23:02:36

+0

你能做什麼?如果你的應用程序基於與數據庫的連接,那麼你可以做的事情並不多。等待連接重新恢復。 – 2013-03-06 23:04:09

+0

有沒有辦法優雅地退化,而不是讓它崩潰= S? – 2013-03-06 23:04:49

相關問題