[英]Check if device has internet connection
我想检查设备是否可以连接互联网。 我找到了很多解决方案,但是在示例中我不能做这样的事情:
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()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.