简体   繁体   English

如何检查Android设备上的网络何时不可用?

[英]How to check when network is not available on android device?

I use android device 我使用的是android设备

and I want when app start, check current network state. 我想在应用启动时检查当前网络状态。

so, I try this. 所以,我尝试这个。

ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERIVCE);
NetworkInfo ethernet = manager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
NetworkInfo wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (wifi.isConnected()) {
   Log.d(TAG, "WIFI isConnected");
} else if (ethernet.isConnected()) {
   Log.d(TAG, "Ethernet isConnected");
} else if (wifi.isAvaiable()) {
   Log.d(TAG, "Wifi not connect, but wifi isAvailable");
} else {
   Log.d(TAG, "not available network");
}

this source check Wi-Fi and Ethernet network state. 此来源检查Wi-Fi和以太网网络状态。

but when unable network. 但是当无法联网时。 not check. 不检查。

My device if use wifi, connect Wireless LAN on my device. 我的设备如果使用wifi,请在我的设备上连接无线局域网。

when disconnect Wireless Lan on my device. 当断开我设备上的无线局域网时。 my source is Check wifi.isAvailable() 我的来源是Check wifi.isAvailable()

in conclusion, 结论,

  1. How to check when network is not available (current source, when network is not available check wifi.isAvailable) 如何检查网络何时不可用(当前来源,网络不可用时检查wifi.isAvailable)

  2. When connect Wireless Lan and Wifi off, check wifi.isAvailable() but When disconnect Wireless Lan and Wifi off , check wifi.isAvailable() How to distinguish from this situation. 当关闭Wireless Lan和Wifi时,请检查wifi.isAvailable()但是当断开Wireless Lan和Wifi时,请wifi.isAvailable()如何区分这种情况。

THANKS. 谢谢。

you should use getActiveNetworkInfo() to check connectivity of currently active default data network--no need to check for particular data network; 您应该使用getActiveNetworkInfo()来检查当前活动的默认数据网络的连通性-无需检查特定的数据网络; be it Ethernet or Wi-Fi. 无论是以太网还是Wi-Fi。

  public static boolean NetAvailable(final Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    final boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    return isConnected;
   }

Try this function 试试这个功能

public boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

and check like this 然后像这样检查

if(isNetworkAvailable(this))
{
System.out.println(""Internet Connected);
}else
{
System.out.println(""Internet Not Connected);
}
public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(
                Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

For knowing working internet state use this snippet 要了解工作中的互联网状态,请使用此代码段

public static boolean isInternetAccess() {
    try {
        HttpURLConnection urlc = (HttpURLConnection) 
            (new URL("http://www.google.com")
            .openConnection());
        urlc.setRequestProperty("User-Agent", "Android");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1500); 
        urlc.connect();
        return (urlc.getResponseCode() == 200);
    } catch (IOException e) {
        Log.e(TAG, "Error checking internet connection", e);
    }

return false;

} }

If this code returns failed result that means network is not available,and call your code for getting available networks. 如果此代码返回失败结果,则意味着网络不可用,然后致电您的代码以获取可用网络。

you need to use BroadcastReceiver for check connectivity. 您需要使用BroadcastReceiver来检查连接性。 when status change it call onReceive() method. 状态更改时,它调用onReceive()方法。

public BroadcastReceiver internetConnectionReciever = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        @SuppressWarnings("static-access")
        NetworkInfo activeWIFIInfo = connectivityManager
                .getNetworkInfo(connectivityManager.TYPE_WIFI);

        if (activeWIFIInfo.isConnected() || activeNetInfo.isConnected()) {

        } 
    }
};

Register Receiver in onResume() and destroy it in onDestroy() 在onResume()中注册Receiver并在onDestroy()中销毁它

 @Override
protected void onResume() {
    super.onResume();
    registerReceiver(internetConnectionReciever, new IntentFilter(
            "android.net.conn.CONNECTIVITY_CHANGE"));

}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(internetConnectionReciever);
}
  public static boolean checkInternetConnection(Context context) {
        try {
            ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            android.net.NetworkInfo ethernet = connec.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);

            if ((wifi != null && wifi.isConnected())
                    || (mobile != null && mobile.isConnected())
                    || (ethernet != null && ethernet.isConnected())) {
                return true;
            }
            log("Connection", "Connection failed");
            return false;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return false;
        }
    }  

Use this method. 使用此方法。 you don't need to check wifi.isAvailable(), just check isConnected() 您不需要检查wifi.isAvailable(),只需检查isConnected()

Try this for checking device online or offline. 尝试此操作以在线或离线检查设备。

private boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM