如何在移动设备中检查WIFI和3G(数据计划)中的网络连接启用或禁用?

Joh*_*ick 7 android

我正在开发一个Android应用程序,在我的申请,我要检查网络连接,比如我要检查在WiFi和3G网络连接(如印度人大多喜欢在移动数据计划),如何检查网络WiFi和3G.naybody我知道,请对此有所了解.

谢谢

Chi*_*rag 38

请试试这个

public static boolean isInternetConnected (Context ctx) {
    ConnectivityManager connectivityMgr = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifi = connectivityMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    NetworkInfo mobile = connectivityMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    // Check if wifi or mobile network is available or not. If any of them is
    // available or connected then it will return true, otherwise false;
    if (wifi != null) {
        if (wifi.isConnected()) {
            return true;
        }
    }
    if (mobile != null) {
        if (mobile.isConnected()) {
            return true;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

请在android清单文件中添加以下权限.

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

  • 无线和移动连接的+1检查:) (4认同)

Piy*_*tel 9

这是代码片段.如果网络启用则返回true,否则返回false

private boolean netCheckin() {
    try {
        ConnectivityManager nInfo = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
        nInfo.getActiveNetworkInfo().isConnectedOrConnecting();
        Log.d(tag, "Net avail:"
            + nInfo.getActiveNetworkInfo().isConnectedOrConnecting());
        ConnectivityManager cm = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            Log.d(tag, "Network available:true");
            return true;
        } else {
            Log.d(tag, "Network available:false");
            return false;
        }
    } catch (Exception e) {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)