2013-07-17 78 views
0

我想檢查設備是否具有網絡連接。我已經找到了很多解決方案,但我不能做這樣的事情例如:檢查設備是否具有網絡連接

if(device has Internet connection){ 
    webview.loadUrl("http://the.url.com") 
} 
else{ 
    Toast.makeText(context, text, duration).show() 
} 
+0

也許這篇文章可以幫助你:http://stackoverflow.com/questions/ 6493517/android-detect-if-device-has-internet-connection –

+0

是的,我已經看到了答案。但請查看第一條評論「如果谷歌在某些國家被禁止,該怎麼辦」 – Enve

+0

您可以將您的loadurl放入try&catch子句中,並在發現錯誤時爲您的消息敬酒。 –

回答

6

將這個方法的類要檢查連接:當你需要

public static boolean isOnline(Context context) { 
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
    if (netInfo != null && netInfo.isConnected()) { 
     return true; 
    } 
    return false; 
} 

然後檢查連接,這樣做(使用你的例子):

if(isOnline(getApplicationContext()){ 
    webview.loadUrl("http://the.url.com") 
} 
else{ 
    Toast.makeText(context, text, duration).show() 
} 

你還可以創建一個類,方法,總是用它從那裏,像ExampleClass.isOnline()。

不要忘記添加到您的AndroidManifest:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
2

這是一個小例子:

try { 
    URL url = new URL("http://the.url.com"); 
    URLConnection conn = url.openConnection(); 
    conn.connect(); 
    webview.loadUrl("http://the.url.com"); 
} catch (MalformedURLException e) { 
    // the URL is not in a valid form 
    Toast.makeText(context, text, duration).show(); 
} catch (IOException e) { 
    // the connection couldn't be established 
    Toast.makeText(context, text, duration).show() 
}