Android设备上如何检查wifi或3g网络

Gov*_*ddy 31 java android

在这里,我的Android设备支持wifi和3G.在此设备上可用的网络的特定时间.因为我的要求是3g可用时我必须上传少量数据.当wifi可用时,必须上传整个数据.所以,我要检查连接是wifi还是3g.请帮我.提前致谢.

Pen*_*m10 54

我用这个:

/**
 * Checks if we have a valid Internet Connection on the device.
 * @param ctx
 * @return True if device has internet
 *
 * Code from: http://www.androidsnippets.org/snippets/131/
 */
public static boolean haveInternet(Context ctx) {

    NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

    if (info == null || !info.isConnected()) {
        return false;
    }
    if (info.isRoaming()) {
        // here is the roaming option you can change it if you want to
        // disable internet while roaming, just return false
        return false;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

你还需要

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Run Code Online (Sandbox Code Playgroud)

在AndroidMainfest.xml中

要获取网络类型,您可以使用以下代码段:

ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

//mobile
State mobile = conMan.getNetworkInfo(0).getState();

//wifi
State wifi = conMan.getNetworkInfo(1).getState();
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
    //mobile
} else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
    //wifi
}
Run Code Online (Sandbox Code Playgroud)

要获得移动网络的类型,我会尝试TelephonyManager#getNetworkTypeNetworkInfo#getSubtypeName


归档时间:

查看次数:

31316 次

最近记录:

8 年,10 月 前