检查网络连接android

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10009804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:10:09  来源:igfitidea点击:

Check network connection android

androidnetworkingconnection

提问by amp

In my application, which I test on emulator, I use the following code to check the network connection (WIFI):

在我在模拟器上测试的应用程序中,我使用以下代码检查网络连接 (WIFI):

    public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

This method returns always true, even if I disable the wireless connection of my computer... Is this caused by the emulator or is it something else?

此方法始终返回true,即使我禁用了计算机的无线连接...这是由模拟器引起的还是其他原因?

If this is not the right way to check network connection, how can I do that?

如果这不是检查网络连接的正确方法,我该怎么做?

回答by Nishant

It's better to (1) pass in the context so that the every activity can invoke this functions, and (2) Make this function static:

最好 (1) 传入上下文,以便每个活动都可以调用此函数,以及 (2) 将此函数设为静态:

 public boolean isNetworkOnline() {
    boolean status=false;
    try{
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getNetworkInfo(0);
        if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
            status= true;
        }else {
            netInfo = cm.getNetworkInfo(1);
            if(netInfo!=null && netInfo.getState()==NetworkInfo.State.CONNECTED)
                status= true;
        }
    }catch(Exception e){
        e.printStackTrace();  
        return false;
    }
    return status;

    }  

回答by SuN

To get getActiveNetworkInfo() to work you need to add the following to the manifest.

要让 getActiveNetworkInfo() 工作,您需要将以下内容添加到清单中。

1. uses-permission android:name="android.permission.INTERNET"
 2. uses-permission
    android:name="android.permission.ACCESS_NETWORK_STATE"

better to use netInfo.isConnected() rather than netInfo.isConnectedOrConnecting

最好使用 netInfo.isConnected() 而不是 netInfo.isConnectedOrConnecting

and also try this

也试试这个

Context.getSystemService(Context.CONNECTIVITY_SERVICE).getNetworkInfo(ConnectivityManager.TYPE_MOBILE)

or

或者

Context.getSystemService(Context.CONNECTIVITY_SERVICE).requestRouteToHost(TYPE_WIFI, int hostAddress)

回答by Ashish Saini

We can check internet connection connected state using below function. Google Android has updated the Android API's function to check the network state. Now in Android latest API's, getAllNetworkInfo()is deprecated. but getAllNetworks()function is only allowed for Build.VERSION.SDK_INT >= 21.Ihave written code for all cases.

我们可以使用以下功能检查互联网连接连接状态。Google Android 已更新 Android API 的功能以检查网络状态。现在在 Android 最新的 API 中,getAllNetworkInfo()已弃用。但getAllNetworks()函数只允许Build.VERSION.SDK_INT >= 21.I为所有情况编写代码。

To check the internet connection, you may call this function.

要检查互联网连接,您可以调用此函数。

public static boolean checkInternetConnection(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
        return false;
    } else if(Build.VERSION.SDK_INT >= 21){
        Network[] info = connectivity.getAllNetworks();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i] != null && connectivity.getNetworkInfo(info[i]).isConnected()) {
                    return true;
                }
            }
        }
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        final NetworkInfo activeNetwork = connectivity.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected()) {
            return true;
        }
    }

    return false;
}

回答by Rodrigo

Use the following class, updated to the last Android version available: Android 10.

使用以下类,更新到最新可用的 Android 版本:Android 10。

回答by Gene Bo

In my case, I turned OFF the Wifi, but forgot about turning off the Data/Mobile network connectivity. Once I did that, the code in original post for this thread worked for me.

就我而言,我关闭了 Wifi,但忘记关闭数据/移动网络连接。一旦我这样做了,这个线程的原始帖子中的代码对我有用。

To recap:

回顾一下:

  1. Go to Settings
  2. Turn Off Wifi
  3. Go to Settings->Data Usage
  4. Turn Off Mobile Data
  1. 前往设置
  2. 关闭无线网络
  3. 转到设置->数据使用
  4. 关闭移动数据

Settings

Settings

Settings->Data Usage

Settings->Data Usage

回答by david m lee

This is how I put it together in a project:

这就是我将它放在一个项目中的方式:

Manifest file:

清单文件:

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

Static Function:

静态功能:

public static boolean isNwConnected(Context context) {
    if (context == null) {
        return true;
    }
    ConnectivityManager connectivityManager = 
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nwInfo = connectivityManager.getActiveNetworkInfo();
    if (nwInfo != null && nwInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}