开发者

How to check the network availability?

I have to connect my app with server using either wifi (if it is available), or gprs (if wifi is not available). Here is my code to check the connection availability

public static final boolean isConnectionAvailable(Activity a)
{  

  ConnectivityManager cm = (ConnectivityManager)a.getSystemService(Context.CONNECTIVITY_SERVICE);

  State mobile = cm.getNetworkInfo(0).getState();

  State wifi = cm.getNetwork开发者_如何学GoInfo(1).getState();

  if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
    {
        return true;
    }
  if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
    {
        return true;
    }

   return false;
}      

Is this a correct way? Can anyone suggest me a better way?


The following very similar approach works, but has the added advantage of not caring what the underlying medium, since it looks as though there is support for more than just WiFi. Maybe these are also covered by mobile, but the docs aren't super clear:

// added as an instance method to an Activity
boolean isNetworkConnectionAvailable() {  
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();     
    if (info == null) return false;
    State network = info.getState();
    return (network == NetworkInfo.State.CONNECTED || network == NetworkInfo.State.CONNECTING);
}     


Network Availability Check :

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}


Or you could use some kotlin implementation

fun Context.isNetworkAvailable(): Boolean {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
return activeNetwork?.isConnectedOrConnecting == true

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜