Android:检查Android设备上的3G或Wifi网络是否已开启或可用。

17

如何在Android设备上以编程方式检查网络是否可用,当我们尝试连接到Wifi和3G等网络时,如何抛出消息或Toast消息。

10个回答

55

为了在开始活动之前检查网络,即3G或WiFi是否可用,我们可以使用以下方法进行验证。

ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

//For 3G check
boolean is3g = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
            .isConnectedOrConnecting();
//For WiFi Check
boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
            .isConnectedOrConnecting();

System.out.println(is3g + " net " + isWifi);

if (!is3g && !isWifi) 
{ 
Toast.makeText(getApplicationContext(),"Please make sure your Network Connection is ON ",Toast.LENGTH_LONG).show();
} 
 else 
{ 
        " Your method what you want to do "
} 

希望这能帮助到某些人。


1
你可以在这里获取相关信息:http://rahulbaradiaa.blogspot.in/2012/07/check-wifi-3g-availability-on-android.html - Rahul Baradia
2
空指针异常:boolean is3g = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting(); - benoffi7
3
正如@benoffi7所说,你需要在调用isConnectedOrConnecting()方法之前测试manager.getNetworkInfo(ConnectivityManager.*)不为空。 - Kikiwa
"getInfoNetwork(int)"现已被弃用。仅供记录(请参阅此StackOverflow答案获取更新版本)。 - Anwar
1
getNetworkInfo()现在已经过时了,因为例如:如果设备上有2个蜂窝网络。 - HungNM2

7
final ConnectivityManager connMgr = (ConnectivityManager)
    this.getSystemService(Context.CONNECTIVITY_SERVICE);

    final android.net.NetworkInfo wifi =
    connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    final android.net.NetworkInfo mobile =
    connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if( wifi.isAvailable() && wifi.getDetailedState() == DetailedState.CONNECTED){
        Toast.makeText(this, "Wifi" , Toast.LENGTH_LONG).show();
    }
    else if( mobile.isAvailable() && mobile.getDetailedState() == DetailedState.CONNECTED ){
        Toast.makeText(this, "Mobile 3G " , Toast.LENGTH_LONG).show();
    }
    else
    {   
        Toast.makeText(this, "No Network " , Toast.LENGTH_LONG).show();
    }

这段代码检查你当前是否连接着wifi或者是使用3G网络,如果你的wifi打开了但是没有连接网络或者是3G信号不稳定,它会用DetailedStates来检测这些细节。


6
您可以使用此方法来检查您的互联网连接是2G、3G还是4G:
public String getNetworkClass(Context context) {
    TelephonyManager mTelephonyManager = (TelephonyManager)
            context.getSystemService(Context.TELEPHONY_SERVICE);
    int networkType = mTelephonyManager.getNetworkType();
    switch (networkType) {
        case TelephonyManager.NETWORK_TYPE_GPRS:
        case TelephonyManager.NETWORK_TYPE_EDGE:
        case TelephonyManager.NETWORK_TYPE_CDMA:
        case TelephonyManager.NETWORK_TYPE_1xRTT:
        case TelephonyManager.NETWORK_TYPE_IDEN:
            return "2G";
        case TelephonyManager.NETWORK_TYPE_UMTS:
        case TelephonyManager.NETWORK_TYPE_EVDO_0:
        case TelephonyManager.NETWORK_TYPE_EVDO_A:
        case TelephonyManager.NETWORK_TYPE_HSDPA:
        case TelephonyManager.NETWORK_TYPE_HSUPA:
        case TelephonyManager.NETWORK_TYPE_HSPA:
        case TelephonyManager.NETWORK_TYPE_EVDO_B:
        case TelephonyManager.NETWORK_TYPE_EHRPD:
        case TelephonyManager.NETWORK_TYPE_HSPAP:
            return "3G";
        case TelephonyManager.NETWORK_TYPE_LTE:
            return "4G";
        default:
            return "Unknown";
    }
}

使用以下方法可以检查 是否有可用的互联网连接,并获取您是通过移动网络还是WiFi访问互联网:

public String getNetworkType(Context context){
    String networkType = null;
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
    if (activeNetwork != null) { // connected to the internet
        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                networkType = "WiFi";
        } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
            networkType = "Mobile";
        }
    } else {
        // not connected to the internet
    }
    return networkType;
}

3
这对我有用。
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();   
String name networkInfo.getTypeName();  

3

Rahul Baradia的答案中包括manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE),然而已被弃用。

以下是针对最新Android SDK的改进方案。

ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
        boolean is3gEnabled = false;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Network[] networks = connManager.getAllNetworks();
            for(Network network: networks)
            {
                NetworkInfo info = connManager.getNetworkInfo(network);
                if(info!=null) {
                    if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                        is3gEnabled = true;
                        break;
                    }
                }
            }
        }
        else
        {
            NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if(mMobile!=null)
                is3gEnabled = true;
        }

1
我们可以使用ConnectivityManager Class来获取与网络相关的任何信息。
它还会在网络连接状态更改时通知应用程序。通过调用此类的实例来获取一个实例。
该类的主要职责是:
  1. 监视网络连接(Wi-Fi、GPRS、UMTS等)
  2. 在网络连接状态更改时发送广播意图
  3. 当与网络的连接丢失时,尝试“故障转移”到另一个网络
  4. 提供API,允许应用程序查询可用网络的粗粒度或细粒度状态
  5. 提供API,允许应用程序请求和选择其数据流量的网络
请注意保留HTML标签。

GetNetworkInfo function return status information about a particular network type.

This method requires the caller to hold the permission

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

     /**
     * Checks the type of data connection that is currently available on the device.
     *
     * @return <code>ConnectivityManager.TYPE_*</code> as a type of internet connection on the
     *This method does not support multiple connected networks
     *             of the same type.
     * device. Returns -1 in case of error or none of
     * <code>ConnectivityManager.TYPE_*</code> is found.
     **/

--

public static int getDataConnectionType(Context ctx) {

        ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager != null && connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null) {
            if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected()) {
                return ConnectivityManager.TYPE_MOBILE;
            } else if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
                return ConnectivityManager.TYPE_WIFI;
            } else
                return -1;
        } else
            return -1;
    }


仅返回与网络类型连接的内容,不返回用户启用的类型。 - kemdo

1
请将以下代码用作 NetworkChecker.java 并在您的代码中重复使用:

package das.soumyadip.util;

import android.net.ConnectivityManager;
import android.util.Log;

public class NetworkChecker {
    private final static String TAG = "NwtworkChecker";

    public static boolean isNetworkConnected(
            final ConnectivityManager connectivityManager) {
        boolean val = false;

        Log.d(TAG, "Checking for Mobile Internet Network");
        final android.net.NetworkInfo mobile = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mobile.isAvailable() && mobile.isConnected()) {
            Log.i(TAG, "Found Mobile Internet Network");
            val = true;
        } else {
            Log.e(TAG, "Mobile Internet Network not Found");
        }

        Log.d(TAG, "Checking for WI-FI Network");
        final android.net.NetworkInfo wifi = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifi.isAvailable() && wifi.isConnected()) {
            Log.i(TAG, "Found WI-FI Network");
            val = true;
        } else {
            Log.e(TAG, "WI-FI Network not Found");
        }

        return val;
    }
}

1
为什么关闭了Wi-Fi(或3G)会出现错误(Log.e(TAG,“WI-FI网络未找到”)0_0?这对于手机和许多可以在没有它的情况下工作(可能是其中一部分)的应用程序来说是一个有效的情况。为什么在此类实用程序中有如此多的日志记录,而不是关键任务代码? - Denis Gladkiy

1
        // TODO Auto-generated method stub
        ConnectivityManager connMgr =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        final android.net.NetworkInfo mobile = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mobile.isAvailable() && mobile.isConnected()) {
            Log.i(TAG, "Found Mobile Internet Network");
            val = true;
        }
        // Checks the user prefs and the network connection. Based on the result, decides
        // whether
        // to refresh the display or keep the current display.
        // If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.
        if (WIFI.equals(sPref) && networkInfo != null
                && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            // If device has its Wi-Fi connection, sets refreshDisplay
            // to true. This causes the display to be refreshed when the user
            // returns to the app.
            refreshDisplay = true;
            Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();

            // If the setting is ANY network and there is a network connection
            // (which by process of elimination would be mobile), sets refreshDisplay to true.
        }

}
        else if (ANY.equals(sPref) && networkInfo != null) {
            refreshDisplay = true;

            // Otherwise, the app can't download content--either because there is no network
            // connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there
            // is no Wi-Fi connection.
            // Sets refreshDisplay to false.
        } else {
            refreshDisplay = false;
            Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();
        }

1
public boolean isInternetAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null) { // connected to the internet
        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
            // connected to wifi
            return true;

        } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
            // connected to the mobile provider's data plan
            return true;
        }
    } else {
        // not connected to the internet
        return false;
    }
    return false;
}

0
在上面的代码中,我没有看到对getNetworkInfo()返回null的检查,根据文档,当请求的网络类型不受支持时会发生这种情况。这意味着在没有3G的设备上,应用程序将因为空指针异常而崩溃。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接