检查设备是否有互联网连接

Env*_*nve 0 java xml connection android

我想检查设备是否有互联网连接.我找到了很多解决方案,但在示例中我不能做这样的事情:

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

Rod*_*cio 7

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

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;
}
Run Code Online (Sandbox Code Playgroud)

然后,当您需要检查连接时,执行此操作(使用您的示例):

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

您也可以在类中创建该方法,并始终从那里使用它,如ExampleClass.isOnline().

不要忘记将其添加到AndroidManifest:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Run Code Online (Sandbox Code Playgroud)