2012-03-28 57 views
0

下面的代码崩溃是没有interenet连接时:崩溃的时候没有互联网连接

public String gourl(String myurl,String params) { 

     URL url; 
     String rasp = ""; 

     try { 
      url = new URL(myurl + params); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(
        url.openStream())); 
      String line = ""; 
      while ((line = rd.readLine()) != null) { 
       rasp=rasp + line; 
      } 

      return rasp; 
     } catch (Exception e) { 
      Log.w("DHA", "EXCEPTIE URL"); 
     }  
     return null; 
} 

我怎样才能防止这种情况发生?

+0

哪个例外? – Blackbelt 2012-03-28 13:11:27

+0

当我写你接受答案的同时。 :) – Sameer 2012-03-28 13:31:09

回答

6

检查连接之前执行的方法,这样的事情:

public boolean isNetworkConnected() { 
     final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
     final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo(); 
     return activeNetwork != null && activeNetwork.getState() == NetworkInfo.State.CONNECTED; 
    } 
+0

非常好的解决方案谢谢。 – opc0de 2012-03-28 13:19:59

+0

如果我打电话给它两次应用程序崩溃 – opc0de 2012-03-28 13:59:25

+3

我使用这种方法 - 从来没有问题。检查权限。并请显示logcat。 – 2012-03-28 14:11:11

1

你检查什么myurlparams中值的方法?

这可能是url.openStream()失败并导致NullPointerException。

这也是有帮助的,而这样做:

Log.w("DHA", "EXCEPTIE URL:" + e.toString()); 

然后你会看到唯一的例外是什么,而不是猜测。

1

检查所有互联网连接

支持WiFi

public boolean isWifi(Context context){ 
    try{ 
    WifiManager wifi=(WifiManager) 

context.getSystemService(Context.WIFI_SERVICE); 
    if(wifi.isWifiEnabled()){ 
    return true; 
    }else{ 
     return false; 
    } 
    } 
    catch(Exception e){ 
     e.getMessage(); 
     return false; 
    } 
} 

其他网络

public boolean isOline(Context context){ 
    try{ 
     ConnectivityManager cm=(ConnectivityManager) 

    context.getSystemService(Context.CONNECTIVITY_SERVICE); 
     if(cm==null) 
      return false; 
     NetworkInfo info=cm.getActiveNetworkInfo(); 
     if(info==null) 
      return false; 
     return info.isConnectedOrConnecting(); 
    } 
    catch(Exception e){ 
     e.getMessage(); 
     return false; 
    } 
} 

如果他们中任何一个存在,那么处理WS别的节目alert.And永远不要忘记提及

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
相关问题