2017-07-19 50 views
-1

我正在制作一个应用程序,用户需要互联网许可,现在假设用户向应用程序提供互联网许可,但互联网已关闭,因此如何给出错误消息,说明互联网已关闭并将其打开。如何在android中关闭互联网时发出错误消息?

+0

此问题是论题 –

+0

是否要为API调用执行此操作? –

回答

0

这是你可以做到的。

private boolean isNetworkConnected() { 
    ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 
      return cm.getActiveNetworkInfo() != null; 
} 

在清单

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

如果装置被连接到互联网这种方法实际上检查(有一种可能性,它连接到一个网络而不是互联网)。

public boolean isInternetAvailable() { 
    try { 
     InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name 
     return !ipAddr.equals(""); 

    } catch (Exception e) { 
     return false; 
    } 

} 
0

我们可以使用ConnectivityManager类来看看,如果互联网连接。 ConnectivityManager并不需要实例,可以使用这种方式的系统 -

if (isNetworkConnected()) 
     // The internet is on, go ahead 
else{ 
     // The internet is not connected, either take them to settings, or ask them to turn it on manually. 
} 

private boolean isNetworkConnected() { 
    ConnectivityManager cm = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE); 

    return cm.getActiveNetworkInfo() != null; 
} 
0

使用ConnectivityManager看到互联网连接与否。

public static boolean isConnected() { 
    ConnectivityManager connectivityManager = (ConnectivityManager) AppController.getInstance().getApplicationContext() 
      .getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo(); 

    if (activeNetwork != null && activeNetwork.isAvailable() && activeNetwork.isConnected() && activeNetwork.isConnectedOrConnecting()) { 
     return true; 
    } else { 
     return false; 
    } 
} 

使用此条件

if (isConnected()) 
     // The internet is connected, do something 
else{ 
     // The internet is not connected, do something 
} 

不要忘了在AndroidManifest.xml

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

我希望能帮助您添加此权限。

相关问题