Android 互联网连接检查问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2753412/
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 07:13:37  来源:igfitidea点击:

Android internet connectivity check problem

androidandroid-permissionsandroid-internet

提问by Charles

I'm new to Android development and working on an Android application that requires the phone to be connected to the internet, through either Wifi, EDGE or 3G.

我是 Android 开发新手,正在开发一个 Android 应用程序,该应用程序需要手机通过 Wifi、EDGE 或 3G 连接到互联网。

This is the code that I'm using to check whether an internet connection is available

这是我用来检查互联网连接是否可用的代码

public static boolean isConnected()
{
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo().isConnectedOrConnecting();
}

I've also set these permissions in the manifest file

我还在清单文件中设置了这些权限

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

This works fine in the emulator running version 1.5 of Android when 3G is enabled, but it crashes when I disable the 3G connection. My application throws a null pointer exception when I call isConnectedOrConnecting(). The same thing also happens on my HTC Desire running Android 2.1.

当启用 3G 时,这在运行 Android 1.5 版的模拟器中运行良好,但是当我禁用 3G 连接时它会崩溃。当我调用 isConnectedOrConnecting() 时,我的应用程序抛出空指针异常。同样的事情也发生在我运行 Android 2.1 的 HTC Desire 上。

Hope that anyone knows the solution to this.

希望任何人都知道解决方案。

Thanks in advance!

提前致谢!

回答by CommonsWare

If the crash is directlyon your line:

如果崩溃直接发生在您的线路上:

return cm.getActiveNetworkInfo().isConnectedOrConnecting();

then that means getActiveNetworkInfo()returned null, because there is no active network -- in that case, your isConnected()method should return false.

那么这意味着getActiveNetworkInfo()返回null,因为没有活动网络——在这种情况下,你的isConnected()方法应该返回false

回答by mutable2112

I wrote this method to handle this:

我写了这个方法来处理这个:

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

One way to do it I guess...

一种方法来做到这一点,我猜...

回答by Dhrupal

To check internet is there or not can be checked only on device......On emulator it may not work.... I have got the following code & its working 100% on android device..... :)

检查互联网是否存在只能在设备上检查......在模拟器上它可能无法工作......我有以下代码及其在Android设备上100%工作...... :)

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tv = (TextView)findViewById(R.id.txt);
    b = checkInternetConnection();


    if(b!=true)
    {
        tv.setText("net is not dr.......");
    }
    else
    {
        tv.setText("net is dr.......");
    }

}
//Check weather Internet connection is available or not
public boolean checkInternetConnection() {
           final ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
           if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() &&    conMgr.getActiveNetworkInfo().isConnected()) {
                 return true;
           } else {
                 System.out.println("Internet Connection Not Present");
               return false;
           }
        }

}

}

回答by Harshid

You have used this snippet.

你已经使用了这个片段。

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;
                  }

      }

回答by Yuval

use this to detemine if connceted to wifi/3g:

使用它来确定是否连接到 wifi/3g:

is3g = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();
    isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
    network = is3g||isWifi;

and this to enable wifi yourself:

这是为了自己启用wifi:

WifiManager wifiManager = (WifiManager) MainWindowYuval.this.getSystemService(Context.WIFI_SERVICE);
                    wifiManager.setWifiEnabled(true);