Example usage for android.net NetworkInfo getExtraInfo

List of usage examples for android.net NetworkInfo getExtraInfo

Introduction

In this page you can find the example usage for android.net NetworkInfo getExtraInfo.

Prototype

@Deprecated
public String getExtraInfo() 

Source Link

Document

Report the extra information about the network state, if any was provided by the lower networking layers.

Usage

From source file:com.fanfou.app.opensource.util.NetworkHelper.java

/**
 * ????/*  w  w w .j  a v a 2  s . c  o m*/
 * 
 * @param context
 * @param httpParams
 */
private static final void checkAndSetProxy(final Context context, final HttpParams httpParams) {
    boolean needCheckProxy = true;

    final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if ((networkInfo == null) || NetworkHelper.WIFI.equalsIgnoreCase(networkInfo.getTypeName())
            || (networkInfo.getExtraInfo() == null)) {
        needCheckProxy = false;
    }
    if (needCheckProxy) {
        final String typeName = networkInfo.getExtraInfo();
        if (NetworkHelper.MOBILE_CTWAP.equalsIgnoreCase(typeName)) {
            final HttpHost proxy = new HttpHost("10.0.0.200", 80);
            httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        } else if (NetworkHelper.MOBILE_CMWAP.equalsIgnoreCase(typeName)
                || NetworkHelper.MOBILE_UNIWAP.equalsIgnoreCase(typeName)
                || NetworkHelper.MOBILE_3GWAP.equalsIgnoreCase(typeName)) {
            final HttpHost proxy = new HttpHost("10.0.0.172", 80);
            httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
    }

    // String defaultProxyHost = android.net.Proxy.getDefaultHost();
    // int defaultProxyPort = android.net.Proxy.getDefaultPort();
    // if (defaultProxyHost != null && defaultProxyHost.length() > 0
    // && defaultProxyPort > 0) {
    // HttpHost proxy = new HttpHost(defaultProxyHost, defaultProxyPort);
    // httpParams.setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
    // }
}

From source file:com.iflytek.android.framework.volley.toolbox.HurlStack.java

/**
 * @param context//from  w  w w  .  j a v a  2  s . c om
 * @return ???<br\>
 *         -1: 1:WIFI <br\>
 *           2:cmnet 3:cmwap <br\>
 *           4:ctnet 5:ctwap <br\>
 *         ?  6:uninet 7:uniwap
 */
public static int getAPNType(Context context) {
    // ?wificmnet?cmwap??noneNet
    // ?wifi > cmnet >cmwap > noneNet
    ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo == null) {
        return -1;
    }
    int nType = networkInfo.getType();
    if (nType == ConnectivityManager.TYPE_WIFI) {
        // wifi
        return 1;
    } else if (nType == ConnectivityManager.TYPE_MOBILE) {
        String type = networkInfo.getExtraInfo();
        Log.d("netType", "netType : " + type);
        if (type.equalsIgnoreCase("cmnet")) {
            // cmnet
            return 2;
        } else if (type.equalsIgnoreCase("cmwap")) {
            // cmwap
            return 3;
        } else if (type.equalsIgnoreCase("ctnet")) {
            // ctnet
            return 4;
        } else if (type.equalsIgnoreCase("ctwap")) {
            // ctwap
            return 5;
        } else if (type.equalsIgnoreCase("uninet")) {
            // uninet
            return 6;
        } else if (type.equalsIgnoreCase("uniwap")) {
            // uniwap
            return 7;
        } else {
            return 2;
        }
    }
    return -1;

}

From source file:org.brandroid.openmanager.fragments.DialogHandler.java

private static String getNetworkInfoInfo(NetworkInfo info) {
    String ret = "";
    ret += info.getSubtypeName() + "/ ";
    if (info.getState() != null)
        ret += "s=" + info.getState().name() + "/ ";
    if (info.getDetailedState() != null)
        ret += "d=" + info.getDetailedState().name() + "/ ";
    if (info.getExtraInfo() != null)
        ret += "e=" + info.getExtraInfo();
    return ret;/*w ww  .j  ava2 s.c o m*/
}

From source file:android_network.hetnet.vpn_service.Util.java

public static String getNetworkInfo(Context context) {
    StringBuilder sb = new StringBuilder();
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ani = cm.getActiveNetworkInfo();
    List<NetworkInfo> listNI = new ArrayList<>();

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        listNI.addAll(Arrays.asList(cm.getAllNetworkInfo()));
    else/*from w  w w. j  a va 2s.  c om*/
        for (Network network : cm.getAllNetworks()) {
            NetworkInfo ni = cm.getNetworkInfo(network);
            if (ni != null)
                listNI.add(ni);
        }

    for (NetworkInfo ni : listNI) {
        sb.append(ni.getTypeName()).append('/').append(ni.getSubtypeName()).append(' ')
                .append(ni.getDetailedState())
                .append(TextUtils.isEmpty(ni.getExtraInfo()) ? "" : " " + ni.getExtraInfo())
                .append(ni.getType() == ConnectivityManager.TYPE_MOBILE
                        ? " " + Util.getNetworkGeneration(ni.getSubtype())
                        : "")
                .append(ni.isRoaming() ? " R" : "")
                .append(ani != null && ni.getType() == ani.getType() && ni.getSubtype() == ani.getSubtype()
                        ? " *"
                        : "")
                .append("\r\n");
    }

    try {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        if (nis != null)
            while (nis.hasMoreElements()) {
                NetworkInterface ni = nis.nextElement();
                if (ni != null && !ni.isLoopback()) {
                    List<InterfaceAddress> ias = ni.getInterfaceAddresses();
                    if (ias != null)
                        for (InterfaceAddress ia : ias)
                            sb.append(ni.getName()).append(' ').append(ia.getAddress().getHostAddress())
                                    .append('/').append(ia.getNetworkPrefixLength()).append(' ')
                                    .append(ni.getMTU()).append(' ').append(ni.isUp() ? '^' : 'v')
                                    .append("\r\n");
                }
            }
    } catch (Throwable ex) {
        sb.append(ex.toString()).append("\r\n");
    }

    if (sb.length() > 2)
        sb.setLength(sb.length() - 2);

    return sb.toString();
}

From source file:com.master.metehan.filtereagle.Util.java

public static String getNetworkInfo(Context context) {
    StringBuilder sb = new StringBuilder();
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ani = cm.getActiveNetworkInfo();
    List<NetworkInfo> listNI = new ArrayList<>();

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        listNI.addAll(Arrays.asList(cm.getAllNetworkInfo()));
    else// w  w  w.  j  av a  2  s. co  m
        for (Network network : cm.getAllNetworks()) {
            NetworkInfo ni = cm.getNetworkInfo(network);
            if (ni != null)
                listNI.add(ni);
        }

    for (NetworkInfo ni : listNI) {
        sb.append(ni.getTypeName()).append('/').append(ni.getSubtypeName()).append(' ')
                .append(ni.getDetailedState())
                .append(TextUtils.isEmpty(ni.getExtraInfo()) ? "" : " " + ni.getExtraInfo())
                .append(ni.getType() == ConnectivityManager.TYPE_MOBILE
                        ? " " + Util.getNetworkGeneration(ni.getSubtype())
                        : "")
                .append(ni.isRoaming() ? " R" : "")
                .append(ani != null && ni.getType() == ani.getType() && ni.getSubtype() == ani.getSubtype()
                        ? " *"
                        : "")
                .append("\r\n");
    }

    try {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        if (nis != null) {
            sb.append("\r\n");
            while (nis.hasMoreElements()) {
                NetworkInterface ni = nis.nextElement();
                if (ni != null) {
                    List<InterfaceAddress> ias = ni.getInterfaceAddresses();
                    if (ias != null)
                        for (InterfaceAddress ia : ias)
                            sb.append(ni.getName()).append(' ').append(ia.getAddress().getHostAddress())
                                    .append('/').append(ia.getNetworkPrefixLength()).append(' ')
                                    .append(ni.getMTU()).append("\r\n");
                }
            }
        }
    } catch (Throwable ex) {
        sb.append(ex.toString()).append("\r\n");
    }

    if (sb.length() > 2)
        sb.setLength(sb.length() - 2);

    return sb.toString();
}

From source file:com.example.testplayer.NetworkManager.java

/**
 * Get the latest network connection information
 *
 * @param info the current active network info
 * @return a JSONObject that represents the network info
 *///  w  w w  . j a  v a 2  s.  c om
private JSONObject getConnectionInfo(NetworkInfo info) {
    String type = TYPE_NONE;
    String extraInfo = "";
    if (info != null) {
        // If we are not connected to any network set type to none
        if (!info.isConnected()) {
            type = TYPE_NONE;
        } else {
            type = getType(info);
        }
        extraInfo = info.getExtraInfo();
    }

    Log.d("CordovaNetworkManager", "Connection Type: " + type);
    Log.d("CordovaNetworkManager", "Connection Extra Info: " + extraInfo);

    JSONObject connectionInfo = new JSONObject();

    try {
        connectionInfo.put("type", type);
        connectionInfo.put("extraInfo", extraInfo);
    } catch (JSONException e) {
    }

    return connectionInfo;
}

From source file:by.zatta.pilight.connection.ConnectionService.java

private boolean addedToPreferences() {
    String currentNetwork = null;
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (!(info == null)) {
        // Log.d(TAG, "networkInfo: " + info.getExtraInfo());
        currentNetwork = info.getExtraInfo();
    }/*w  w  w  . ja  va 2 s  .c o m*/
    WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if (!(wifiInfo == null)) {
        // Log.d(TAG, "wifiInfo:" + wifiInfo.getSSID());
        currentNetwork = wifiInfo.getSSID();
    }
    if (currentNetwork == null)
        return false;

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(aCtx);
    String previous = prefs.getString("networks_known", "");
    // Log.d(TAG, previous);
    currentNetwork = currentNetwork.replace("\"", "");
    if (previous.contains(currentNetwork)) {
        // Log.d(TAG, previous + " did contain " + currentNetwork);
        return false;
    } else {
        previous = previous + "|&|" + currentNetwork;
        // Log.d(TAG, previous);
        Editor edit = prefs.edit();
        edit.putString("networks_known", previous);
        edit.commit();
        return true;
    }
}

From source file:org.openchaos.android.fooping.service.PingService.java

@Override
protected void onHandleIntent(Intent intent) {
    String clientID = prefs.getString("ClientID", "unknown");
    long ts = System.currentTimeMillis();

    Log.d(tag, "onHandleIntent()");

    // always send ping
    if (true) {//from www  . j av a 2s  .  c o  m
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "ping");
            json.put("ts", ts);

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/training/monitoring-device-state/battery-monitoring.html
    // http://developer.android.com/reference/android/os/BatteryManager.html
    if (prefs.getBoolean("UseBattery", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "battery");
            json.put("ts", ts);

            Intent batteryStatus = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            if (batteryStatus != null) {
                JSONObject bat_data = new JSONObject();

                int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                if (level >= 0 && scale > 0) {
                    bat_data.put("pct", roundValue(((double) level / (double) scale) * 100, 2));
                } else {
                    Log.w(tag, "Battery level unknown");
                    bat_data.put("pct", -1);
                }
                bat_data.put("health", batteryStatus.getIntExtra(BatteryManager.EXTRA_HEALTH, -1));
                bat_data.put("status", batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1));
                bat_data.put("plug", batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1));
                bat_data.put("volt", batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1));
                bat_data.put("temp", batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1));
                bat_data.put("tech", batteryStatus.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY));
                // bat_data.put("present", batteryStatus.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false));

                json.put("battery", bat_data);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/guide/topics/location/strategies.html
    // http://developer.android.com/reference/android/location/LocationManager.html
    if (prefs.getBoolean("UseGPS", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "loc_gps");
            json.put("ts", ts);

            if (lm == null) {
                lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            }

            Location last_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (last_loc != null) {
                JSONObject loc_data = new JSONObject();

                loc_data.put("ts", last_loc.getTime());
                loc_data.put("lat", last_loc.getLatitude());
                loc_data.put("lon", last_loc.getLongitude());
                if (last_loc.hasAltitude())
                    loc_data.put("alt", roundValue(last_loc.getAltitude(), 4));
                if (last_loc.hasAccuracy())
                    loc_data.put("acc", roundValue(last_loc.getAccuracy(), 4));
                if (last_loc.hasSpeed())
                    loc_data.put("speed", roundValue(last_loc.getSpeed(), 4));
                if (last_loc.hasBearing())
                    loc_data.put("bearing", roundValue(last_loc.getBearing(), 4));

                json.put("loc_gps", loc_data);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    if (prefs.getBoolean("UseNetwork", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "loc_net");
            json.put("ts", ts);

            if (lm == null) {
                lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            }

            Location last_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (last_loc != null) {
                JSONObject loc_data = new JSONObject();

                loc_data.put("ts", last_loc.getTime());
                loc_data.put("lat", last_loc.getLatitude());
                loc_data.put("lon", last_loc.getLongitude());
                if (last_loc.hasAltitude())
                    loc_data.put("alt", roundValue(last_loc.getAltitude(), 4));
                if (last_loc.hasAccuracy())
                    loc_data.put("acc", roundValue(last_loc.getAccuracy(), 4));
                if (last_loc.hasSpeed())
                    loc_data.put("speed", roundValue(last_loc.getSpeed(), 4));
                if (last_loc.hasBearing())
                    loc_data.put("bearing", roundValue(last_loc.getBearing(), 4));

                json.put("loc_net", loc_data);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/reference/android/net/wifi/WifiManager.html
    if (prefs.getBoolean("UseWIFI", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "wifi");
            json.put("ts", ts);

            if (wm == null) {
                wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            }

            List<ScanResult> wifiScan = wm.getScanResults();
            if (wifiScan != null) {
                JSONArray wifi_list = new JSONArray();

                for (ScanResult wifi : wifiScan) {
                    JSONObject wifi_data = new JSONObject();

                    wifi_data.put("BSSID", wifi.BSSID);
                    wifi_data.put("SSID", wifi.SSID);
                    wifi_data.put("freq", wifi.frequency);
                    wifi_data.put("level", wifi.level);
                    // wifi_data.put("cap", wifi.capabilities);
                    // wifi_data.put("ts", wifi.timestamp);

                    wifi_list.put(wifi_data);
                }

                json.put("wifi", wifi_list);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // TODO: cannot poll sensors. register receiver to cache sensor data
    // http://developer.android.com/guide/topics/sensors/sensors_overview.html
    // http://developer.android.com/reference/android/hardware/SensorManager.html
    if (prefs.getBoolean("UseSensors", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "sensors");
            json.put("ts", ts);

            if (sm == null) {
                sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            }

            List<Sensor> sensors = sm.getSensorList(Sensor.TYPE_ALL);
            if (sensors != null) {
                JSONArray sensor_list = new JSONArray();

                for (Sensor sensor : sensors) {
                    JSONObject sensor_info = new JSONObject();

                    sensor_info.put("name", sensor.getName());
                    sensor_info.put("type", sensor.getType());
                    sensor_info.put("vendor", sensor.getVendor());
                    sensor_info.put("version", sensor.getVersion());
                    sensor_info.put("power", roundValue(sensor.getPower(), 4));
                    sensor_info.put("resolution", roundValue(sensor.getResolution(), 4));
                    sensor_info.put("range", roundValue(sensor.getMaximumRange(), 4));

                    sensor_list.put(sensor_info);
                }

                json.put("sensors", sensor_list);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
    // http://developer.android.com/reference/android/net/ConnectivityManager.html
    if (prefs.getBoolean("UseConn", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "conn");
            json.put("ts", ts);

            if (cm == null) {
                cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            }

            // TODO: add active/all preferences below UseConn
            if (prefs.getBoolean("UseConnActive", true)) {
                NetworkInfo net = cm.getActiveNetworkInfo();
                if (net != null) {
                    JSONObject net_data = new JSONObject();

                    net_data.put("type", net.getTypeName());
                    net_data.put("subtype", net.getSubtypeName());
                    net_data.put("connected", net.isConnected());
                    net_data.put("available", net.isAvailable());
                    net_data.put("roaming", net.isRoaming());
                    net_data.put("failover", net.isFailover());
                    if (net.getReason() != null)
                        net_data.put("reason", net.getReason());
                    if (net.getExtraInfo() != null)
                        net_data.put("extra", net.getExtraInfo());

                    json.put("conn_active", net_data);
                }
            }

            if (prefs.getBoolean("UseConnAll", false)) {
                NetworkInfo[] nets = cm.getAllNetworkInfo();
                if (nets != null) {
                    JSONArray net_list = new JSONArray();

                    for (NetworkInfo net : nets) {
                        JSONObject net_data = new JSONObject();

                        net_data.put("type", net.getTypeName());
                        net_data.put("subtype", net.getSubtypeName());
                        net_data.put("connected", net.isConnected());
                        net_data.put("available", net.isAvailable());
                        net_data.put("roaming", net.isRoaming());
                        net_data.put("failover", net.isFailover());
                        if (net.getReason() != null)
                            net_data.put("reason", net.getReason());
                        if (net.getExtraInfo() != null)
                            net_data.put("extra", net.getExtraInfo());

                        net_list.put(net_data);
                    }

                    json.put("conn_all", net_list);
                }
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    if (!PingServiceReceiver.completeWakefulIntent(intent)) {
        Log.w(tag, "completeWakefulIntent() failed. no active wake lock?");
    }
}

From source file:com.landenlabs.all_devtool.NetFragment.java

public void updateList() {
    // Time today = new Time(Time.getCurrentTimezone());
    // today.setToNow();
    // today.format(" %H:%M:%S")
    Date dt = new Date();
    m_titleTime.setText(m_timeFormat.format(dt));

    boolean expandAll = m_list.isEmpty();
    m_list.clear();/*from  w w w  .java  2 s.c  o  m*/

    // Swap colors
    int color = m_rowColor1;
    m_rowColor1 = m_rowColor2;
    m_rowColor2 = color;

    ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);

    try {
        String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        addBuild("Android ID", androidIDStr);

        try {
            AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext());
            final String adIdStr = adInfo.getId();
            final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
            addBuild("Ad ID", adIdStr);
        } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).
        } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
        }

        /*
        try {
        InstanceID instanceID = InstanceID.getInstance(getContext());
        if (instanceID != null) {
            // Requires a Google Developer project ID.
            String authorizedEntity = "<need to make this on google developer site>";
            instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            addBuild("Instance ID", instanceID.getId());
        }
        } catch (Exception ex) {
        }
        */

        ConfigurationInfo info = actMgr.getDeviceConfigurationInfo();
        addBuild("OpenGL", info.getGlEsVersion());
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // --------------- Connection Services -------------
    try {
        ConnectivityManager connMgr = (ConnectivityManager) getActivity()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
        if (netInfo != null) {
            Map<String, String> netListStr = new LinkedHashMap<String, String>();

            putIf(netListStr, "Available", "Yes", netInfo.isAvailable());
            putIf(netListStr, "Connected", "Yes", netInfo.isConnected());
            putIf(netListStr, "Connecting", "Yes", !netInfo.isConnected() && netInfo.isConnectedOrConnecting());
            putIf(netListStr, "Roaming", "Yes", netInfo.isRoaming());
            putIf(netListStr, "Extra", netInfo.getExtraInfo(), !TextUtils.isEmpty(netInfo.getExtraInfo()));
            putIf(netListStr, "WhyFailed", netInfo.getReason(), !TextUtils.isEmpty(netInfo.getReason()));
            if (Build.VERSION.SDK_INT >= 16) {
                putIf(netListStr, "Metered", "Avoid heavy use", connMgr.isActiveNetworkMetered());
            }

            netListStr.put("NetworkType", netInfo.getTypeName());
            if (connMgr.getAllNetworkInfo().length > 1) {
                netListStr.put("Available Networks:", " ");
                for (NetworkInfo netI : connMgr.getAllNetworkInfo()) {
                    if (netI.isAvailable()) {
                        netListStr.put(" " + netI.getTypeName(), netI.isAvailable() ? "Yes" : "No");
                    }
                }
            }

            if (netInfo.isConnected()) {
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                            .hasMoreElements();) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                                .hasMoreElements();) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress()) {
                                if (inetAddress.getHostAddress() != null) {
                                    String ipType = (inetAddress instanceof Inet4Address) ? "IPv4" : "IPv6";
                                    netListStr.put(intf.getName() + " " + ipType, inetAddress.getHostAddress());
                                }
                                // if (!TextUtils.isEmpty(inetAddress.getHostName()))
                                //     listStr.put( "HostName", inetAddress.getHostName());
                            }
                        }
                    }
                } catch (Exception ex) {
                    m_log.e("Network %s", ex.getMessage());
                }
            }

            addBuild("Network...", netListStr);
        }
    } catch (Exception ex) {
        m_log.e("Network %s", ex.getMessage());
    }

    // --------------- Telephony Services -------------
    TelephonyManager telephonyManager = (TelephonyManager) getActivity()
            .getSystemService(Context.TELEPHONY_SERVICE);
    if (telephonyManager != null) {
        Map<String, String> cellListStr = new LinkedHashMap<String, String>();
        try {
            cellListStr.put("Version", telephonyManager.getDeviceSoftwareVersion());
            cellListStr.put("Number", telephonyManager.getLine1Number());
            cellListStr.put("Service", telephonyManager.getNetworkOperatorName());
            cellListStr.put("Roaming", telephonyManager.isNetworkRoaming() ? "Yes" : "No");
            cellListStr.put("Type", getNetworkTypeName(telephonyManager.getNetworkType()));

            if (Build.VERSION.SDK_INT >= 17) {
                if (telephonyManager.getAllCellInfo() != null) {
                    for (CellInfo cellInfo : telephonyManager.getAllCellInfo()) {
                        String cellName = cellInfo.getClass().getSimpleName();
                        int level = 0;
                        if (cellInfo instanceof CellInfoCdma) {
                            level = ((CellInfoCdma) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoGsm) {
                            level = ((CellInfoGsm) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoLte) {
                            level = ((CellInfoLte) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoWcdma) {
                            if (Build.VERSION.SDK_INT >= 18) {
                                level = ((CellInfoWcdma) cellInfo).getCellSignalStrength().getLevel();
                            }
                        }
                        cellListStr.put(cellName, "Level% " + String.valueOf(100 * level / 4));
                    }
                }
            }

            for (NeighboringCellInfo cellInfo : telephonyManager.getNeighboringCellInfo()) {
                int level = cellInfo.getRssi();
                cellListStr.put("Cell level%", String.valueOf(100 * level / 31));
            }

        } catch (Exception ex) {
            m_log.e("Cell %s", ex.getMessage());
        }

        if (!cellListStr.isEmpty()) {
            addBuild("Cell...", cellListStr);
        }
    }

    // --------------- Bluetooth Services (API18) -------------
    if (Build.VERSION.SDK_INT >= 18) {
        try {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (bluetoothAdapter != null) {

                Map<String, String> btListStr = new LinkedHashMap<String, String>();

                btListStr.put("Enabled", bluetoothAdapter.isEnabled() ? "yes" : "no");
                btListStr.put("Name", bluetoothAdapter.getName());
                btListStr.put("ScanMode", String.valueOf(bluetoothAdapter.getScanMode()));
                btListStr.put("State", String.valueOf(bluetoothAdapter.getState()));
                Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
                // If there are paired devices
                if (pairedDevices.size() > 0) {
                    // Loop through paired devices
                    for (BluetoothDevice device : pairedDevices) {
                        // Add the name and address to an array adapter to show in a ListView
                        btListStr.put("Paired:" + device.getName(), device.getAddress());
                    }
                }

                BluetoothManager btMgr = (BluetoothManager) getActivity()
                        .getSystemService(Context.BLUETOOTH_SERVICE);
                if (btMgr != null) {
                    // btMgr.getAdapter().
                }
                addBuild("Bluetooth", btListStr);
            }

        } catch (Exception ex) {

        }
    }

    // --------------- Wifi Services -------------
    final WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);

    if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) {

        if (mSystemBroadcastReceiver == null) {
            mSystemBroadcastReceiver = new SystemBroadcastReceiver(wifiMgr);
            getActivity().registerReceiver(mSystemBroadcastReceiver, INTENT_FILTER_SCAN_AVAILABLE);
        }

        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (wifiMgr.getScanResults() == null || wifiMgr.getScanResults().size() != mLastScanSize) {
                mLastScanSize = wifiMgr.getScanResults().size();
                wifiMgr.startScan();
            }
        }

        Map<String, String> wifiListStr = new LinkedHashMap<String, String>();
        try {
            DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();

            wifiListStr.put("DNS1", Formatter.formatIpAddress(dhcpInfo.dns1));
            wifiListStr.put("DNS2", Formatter.formatIpAddress(dhcpInfo.dns2));
            wifiListStr.put("Default Gateway", Formatter.formatIpAddress(dhcpInfo.gateway));
            wifiListStr.put("IP Address", Formatter.formatIpAddress(dhcpInfo.ipAddress));
            wifiListStr.put("Subnet Mask", Formatter.formatIpAddress(dhcpInfo.netmask));
            wifiListStr.put("Server IP", Formatter.formatIpAddress(dhcpInfo.serverAddress));
            wifiListStr.put("Lease Time(sec)", String.valueOf(dhcpInfo.leaseDuration));

            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            if (wifiInfo != null) {
                wifiListStr.put("LinkSpeed Mbps", String.valueOf(wifiInfo.getLinkSpeed()));
                int numberOfLevels = 10;
                int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1);
                wifiListStr.put("Signal%", String.valueOf(100 * level / numberOfLevels));
                if (Build.VERSION.SDK_INT >= 23) {
                    wifiListStr.put("MAC", getMacAddr());
                } else {
                    wifiListStr.put("MAC", wifiInfo.getMacAddress());
                }
            }

        } catch (Exception ex) {
            m_log.e("Wifi %s", ex.getMessage());
        }

        if (!wifiListStr.isEmpty()) {
            addBuild("WiFi...", wifiListStr);
        }

        try {
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(getContext(),
                            Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                List<ScanResult> listWifi = wifiMgr.getScanResults();
                if (listWifi != null && !listWifi.isEmpty()) {
                    int idx = 0;

                    for (ScanResult scanResult : listWifi) {
                        Map<String, String> wifiScanListStr = new LinkedHashMap<String, String>();
                        wifiScanListStr.put("SSID", scanResult.SSID);
                        if (Build.VERSION.SDK_INT >= 23) {
                            wifiScanListStr.put("  Name", scanResult.operatorFriendlyName.toString());
                            wifiScanListStr.put("  Venue", scanResult.venueName.toString());
                        }

                        //        wifiScanListStr.put("  BSSID ",scanResult.BSSID);
                        wifiScanListStr.put("  Capabilities", scanResult.capabilities);
                        //       wifiScanListStr.put("  Center Freq", String.valueOf(scanResult.centerFreq0));
                        //       wifiScanListStr.put("  Freq width", String.valueOf(scanResult.channelWidth));
                        wifiScanListStr.put("  Level, Freq",
                                String.format("%d, %d", scanResult.level, scanResult.frequency));
                        if (Build.VERSION.SDK_INT >= 17) {
                            Date wifiTime = new Date(scanResult.timestamp);
                            wifiScanListStr.put("  Time", wifiTime.toLocaleString());
                        }
                        addBuild(String.format("WiFiScan #%d", ++idx), wifiScanListStr);
                    }
                }
            }
        } catch (Exception ex) {
            m_log.e("WifiList %s", ex.getMessage());
        }

        try {
            List<WifiConfiguration> listWifiCfg = wifiMgr.getConfiguredNetworks();

            for (WifiConfiguration wifiCfg : listWifiCfg) {
                Map<String, String> wifiCfgListStr = new LinkedHashMap<String, String>();
                if (Build.VERSION.SDK_INT >= 23) {
                    wifiCfgListStr.put("Name", wifiCfg.providerFriendlyName);
                }
                wifiCfgListStr.put("SSID", wifiCfg.SSID);
                String netStatus = "";
                switch (wifiCfg.status) {
                case WifiConfiguration.Status.CURRENT:
                    netStatus = "Connected";
                    break;
                case WifiConfiguration.Status.DISABLED:
                    netStatus = "Disabled";
                    break;
                case WifiConfiguration.Status.ENABLED:
                    netStatus = "Enabled";
                    break;
                }
                wifiCfgListStr.put(" Status", netStatus);
                wifiCfgListStr.put(" Priority", String.valueOf(wifiCfg.priority));
                if (null != wifiCfg.wepKeys) {
                    //               wifiCfgListStr.put(" wepKeys", TextUtils.join(",", wifiCfg.wepKeys));
                }
                String protocols = "";
                if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.RSN))
                    protocols = "RSN ";
                if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.WPA))
                    protocols = protocols + "WPA ";
                wifiCfgListStr.put(" Protocols", protocols);

                String keyProt = "";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE))
                    keyProt = "none";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP))
                    keyProt = "WPA+EAP ";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK))
                    keyProt = "WPA+PSK ";
                wifiCfgListStr.put(" Keys", keyProt);

                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) {
                    // Remove network connections with no Password.
                    // wifiMgr.removeNetwork(wifiCfg.networkId);
                }

                addBuild("WiFiCfg #" + wifiCfg.networkId, wifiCfgListStr);
            }

        } catch (Exception ex) {
            m_log.e("Wifi Cfg List %s", ex.getMessage());
        }
    }

    if (expandAll) {
        // updateList();
        int count = m_list.size();
        for (int position = 0; position < count; position++)
            m_listView.expandGroup(position);
    }

    m_adapter.notifyDataSetChanged();
}

From source file:com.codename1.impl.android.AndroidImplementation.java

public String getCurrentAccessPoint() {

    ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info == null) {
        return null;
    }//from   w  ww  .  j  a  v a  2s.  co  m
    String apName = info.getTypeName() + "_" + info.getSubtypeName();
    if (info.getExtraInfo() != null) {
        apName += "_" + info.getExtraInfo();
    }
    return apName;
}