Java 检查设备是否具有internet连接

Java 检查设备是否具有internet连接,java,android,xml,connection,Java,Android,Xml,Connection,我想检查设备是否连接了internet。我已经找到了很多解决方案,但我无法在示例中执行类似的操作: if(device has Internet connection){ webview.loadUrl("http://the.url.com") } else{ Toast.makeText(context, text, duration).show() } 将此方法放入要检查连接性的类中: public static boolean isOnline(Context cont

我想检查设备是否连接了internet。我已经找到了很多解决方案,但我无法在示例中执行类似的操作:

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

将此方法放入要检查连接性的类中:

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" />

这是一个小例子:

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

也许这篇文章可以帮助你:是的,我已经看到了答案。但是请检查第一条评论如果谷歌在某些国家被禁止怎么办?你可以把你的loadurl放在一个try&catch子句中,如果它发现了错误,你可以为你的消息干杯。@Andreaoid你能用一个代码回答吗,我是android应用程序的新手。