[英]Check if device has internet connection
I want to check if the device has internet connection. 我想检查设备是否可以连接互联网。 I have found a lot of solutions but I can't do something like this in example:
我找到了很多解决方案,但是在示例中我不能做这样的事情:
if(device has Internet connection){
webview.loadUrl("http://the.url.com")
}
else{
Toast.makeText(context, text, duration).show()
}
Put this method in the class you want to check connectivity: 将此方法放在要检查连接性的类中:
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;
}
Then when you need to check connection, do this (using your example): 然后,当您需要检查连接时,请执行此操作(使用您的示例):
if(isOnline(getApplicationContext()){
webview.loadUrl("http://the.url.com")
}
else{
Toast.makeText(context, text, duration).show()
}
You can also create that method in a class and always use it from there, like ExampleClass.isOnline(). 您还可以在类中创建该方法,并始终从那里开始使用它,例如ExampleClass.isOnline()。
Do not forget to add this to your AndroidManifest: 不要忘记将其添加到您的AndroidManifest中:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
This is a small example: 这是一个小例子:
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.