如何检查android中的蜂窝网络连接

时间:2015-04-08 08:47:23

标签: android

目前,我正在寻找获得蜂窝网络可用性的具体解决方案。为此,我想分享一个场景: 假设我正在接收蜂窝连接,但数据连接被禁用,在这种情况下它应该给我积极的结果但是当我超出覆盖范围或飞行模式为ON 时它应该返回false。我尝试过stackoverflow中的几个代码:例如Check Network connections in androidCheck mobile network connectivity & What does NetworkInfo.State SUSPENDED indicate? 但它们仍然不是我想要的。 我尝试过的其他几个代码很少:

public String getCellularState(Context context){

           if(mPhoneState!=null &&   mPhoneState.getState()==ServiceState.STATE_IN_SERVICE){
            return "Available";
        }
        else{
            return "Not Available";
        }
}

以及

public String getOperator()
     { 
        TelephonyManager manager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
          opeartorName = manager.getSimOperator();
          return opeartorName; 
     }

但没有成功,请建议正确的方法,也不要将其与数据连接相关联

4 个答案:

答案 0 :(得分:0)

检查此方法(如果连接到网络,则返回true):

public static boolean checkConnectivity(Context ctx) {
        boolean bConectado = false;
        ConnectivityManager connec = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] redes = connec.getAllNetworkInfo();

        for (int i = 0; i < 2; i++) {
            if (redes[i].getState() == NetworkInfo.State.CONNECTED) {
                bConectado = true;
            }
        }
        return bConectado;
    }

我认为它来自Stack Overflow的其他帖子,但我不记得链接。

要查看您是否拥有真正的连接,可以通过ping到Google DNS进行检查(例如How to Ping External IP from Java Android):

public static boolean executeCammand(){
        System.out.println(" executeCammand");
        Runtime runtime = Runtime.getRuntime();
        try
        {
            Process  mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int mExitValue = mIpAddrProcess.waitFor();
            System.out.println(" mExitValue "+mExitValue);
            if(mExitValue==0){
                return true;
            }else{
                return false;
            }
        }
        catch (InterruptedException ignore)
        {
            ignore.printStackTrace();
            System.out.println(" Exception:"+ignore);
        }
        catch (IOException e)
        {
            e.printStackTrace();
            System.out.println(" Exception:"+e);
        }
        return false;
    }

但在我看来,这不是最好的选择。

答案 1 :(得分:0)

请检查以下内容并按要求修改:

public boolean getNetworkState() {
    boolean network = false;
    boolean data = false;
    ConnectivityManager connectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] infos = connectivity.getAllNetworkInfo();
    for (int i = 0; i < infos.length; i++) {
        if(infos[i].isAvailable()){
            network = true;
        }
        if(infos[i].isConnected()){
            data = true;
        }   
    }

    if(network)
        if(!data)
            return true;

    return false;
}

如果存在网络之一且数据连接未激活,则返回true,否则返回false。 isAvailable将返回网络可用性,isConnected将返回数据一致性。

答案 2 :(得分:0)

/**
 * Checking whether internet connection is available or not using wifi as well as mobile data network.
 * 
 * @param nContext
 * @return true if net connection is avaible otherwise false
 */
public static boolean isNetworkAvailable(Context nContext) {
    boolean isNetAvailable = false;
    if (nContext != null) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) nContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (mConnectivityManager != null) {
            boolean mobileNetwork = false;
            boolean wifiNetwork = false;
            boolean mobileNetworkConnecetd = false;
            boolean wifiNetworkConnecetd = false;
            NetworkInfo mobileInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifiInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mobileInfo != null)
                mobileNetwork = mobileInfo.isAvailable();
            if (wifiInfo != null)
                wifiNetwork = wifiInfo.isAvailable();
            if (wifiNetwork == true || mobileNetwork == true) {
                if (mobileInfo != null)
                    mobileNetworkConnecetd = mobileInfo
                            .isConnectedOrConnecting();
                wifiNetworkConnecetd = wifiInfo.isConnectedOrConnecting();
            }
            isNetAvailable = (mobileNetworkConnecetd || wifiNetworkConnecetd);
        }
    }
    return isNetAvailable;

}

答案 3 :(得分:0)

试试这个

public class ConnectionDetector {
    private static Context _context;

    public ConnectionDetector(Context context){
        this._context = context;
    }

    public static boolean isConnectingToInternet(){ boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager)_context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedWifi || haveConnectedMobile;}//here is change to take which we want

}
add these permissions in manifest file

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