Example usage for android.telephony TelephonyManager getNetworkOperatorName

List of usage examples for android.telephony TelephonyManager getNetworkOperatorName

Introduction

In this page you can find the example usage for android.telephony TelephonyManager getNetworkOperatorName.

Prototype

public String getNetworkOperatorName() 

Source Link

Document

Returns the alphabetic name of current registered operator.

Usage

From source file:org.restcomm.app.qoslib.Utils.QosInfo.java

/**
 * Called Internally to initialize all of the current measurements for every type of connected newtork
 * This is like a snapshot of everything at this moment in time
 * The information comes from various sources and it mainly fetched from the database for this call, or from APIs such as WiFi
 *///  w  w w  .  j  a va  2  s . c  om
private void updateFromDB() {
    Cursor sig_cursor = null;
    Cursor cell_cursor = null;

    try {
        Uri signalUri = UriMatch.SIGNAL_STRENGTHS.getContentUri();
        Uri limitSignalUri = signalUri.buildUpon().appendQueryParameter("limit", "1").build();
        // sig_cursor = managedQuery(

        Provider dbProvider = ReportManager.getInstance(context.getApplicationContext()).getDBProvider();
        if (dbProvider == null) {
            return;
        }

        sig_cursor = dbProvider.query(UriMatch.SIGNAL_STRENGTHS.getContentUri(), null, null, null,
                Tables.TIMESTAMP_COLUMN_NAME + " DESC");

        sig_cursor.moveToFirst();

        Uri baseStationTable = (UriMatch.BASE_STATIONS
                .getContentUri()/*telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA
                                ? UriMatchOld.BASE_STATIONS_CDMA.getContentUri()
                                : UriMatchOld.BASE_STATIONS_GSM.getContentUri()*/
        );
        Uri limitBSUri = baseStationTable.buildUpon().appendQueryParameter("limit", "1").build();

        // Cursor cell_cursor = managedQuery(
        cell_cursor = dbProvider.query(limitBSUri, null, null, null, Tables.TIMESTAMP_COLUMN_NAME + " DESC");

        cell_cursor.moveToFirst();

        int LowIndex = cell_cursor.getColumnIndex(Tables.BaseStations.BS_LOW);
        int MidIndex = cell_cursor.getColumnIndex(Tables.BaseStations.BS_MID);
        int HighIndex = cell_cursor.getColumnIndex(Tables.BaseStations.BS_HIGH);
        int CodeIndex = cell_cursor.getColumnIndex(Tables.BaseStations.BS_CODE);
        int BandIndex = cell_cursor.getColumnIndex(Tables.BaseStations.BS_BAND);
        int ChanIndex = cell_cursor.getColumnIndex(Tables.BaseStations.BS_CHAN);
        int netTypeIndex = cell_cursor.getColumnIndex(Tables.BaseStations.NET_TYPE);
        String netType = cell_cursor.getString(netTypeIndex);
        int bsLow = cell_cursor.getInt(LowIndex);
        int bsMid = cell_cursor.getInt(MidIndex);
        int bsHigh = cell_cursor.getInt(HighIndex);
        int bsCode = cell_cursor.getInt(CodeIndex);
        int bsBand = cell_cursor.getInt(BandIndex);
        int bsChan = cell_cursor.getInt(ChanIndex);
        if (netType.equals("cdma")) {
            if (LowIndex != -1)
                BID = bsLow;
            if (MidIndex != -1)
                NID = bsMid;
            if (HighIndex != -1)
                SID = bsHigh;
        } else if (netType.equals("gsm")) {
            if (LowIndex != -1) {
                RNC = bsMid;
                CellID = cell_cursor.getInt(LowIndex);
            }
            // the network Id is kept 0 for gsm phones
            if (HighIndex != -1)
                LAC = bsHigh;
            if (bsCode > 0 && bsCode < 1000)
                PSC = bsCode;
            else
                PSC = 0;
            if (bsBand > 0)
                Band = bsBand;
            else
                Band = 0;
            if (bsChan > 0)
                Channel = bsChan;
            else
                Channel = 0;
        }

        if (sig_cursor.getCount() != 0) {
            int signalIndex = sig_cursor.getColumnIndex(Tables.SignalStrengths.SIGNAL);
            int signal2GIndex = sig_cursor.getColumnIndex(Tables.SignalStrengths.SIGNAL2G);
            int rsrpIndex = sig_cursor.getColumnIndex(Tables.SignalStrengths.LTE_RSRP);
            int rsrqIndex = sig_cursor.getColumnIndex(Tables.SignalStrengths.LTE_RSRQ);
            int lteSnrIndex = sig_cursor.getColumnIndex(Tables.SignalStrengths.LTE_SNR);
            int lteSignalIndex = sig_cursor.getColumnIndex(Tables.SignalStrengths.LTE_SIGNAL);
            int lteCqiIndex = sig_cursor.getColumnIndex(Tables.SignalStrengths.LTE_CQI);
            int ecioIndex = sig_cursor.getColumnIndex(Tables.SignalStrengths.ECI0);
            int ecnoIndex = sig_cursor.getColumnIndex(Tables.SignalStrengths.ECN0);
            int snrIndex = sig_cursor.getColumnIndex(Tables.SignalStrengths.SNR);
            int berIndex = sig_cursor.getColumnIndex(Tables.SignalStrengths.BER);
            int rscpIndex = sig_cursor.getColumnIndex(Tables.SignalStrengths.RSCP);
            int tierIndex = sig_cursor.getColumnIndex(Tables.SignalStrengths.COVERAGE);
            Integer tier = sig_cursor.isNull(tierIndex) ? null : sig_cursor.getInt(tierIndex);
            Integer rssi = sig_cursor.isNull(signalIndex) ? null : sig_cursor.getInt(signalIndex);
            Integer rssi2G = sig_cursor.isNull(signal2GIndex) ? null : sig_cursor.getInt(signal2GIndex);
            Integer rsrp = sig_cursor.isNull(rsrpIndex) ? null : sig_cursor.getInt(rsrpIndex);
            Float lteSnr = (sig_cursor.isNull(lteSnrIndex) ? null : (float) sig_cursor.getInt(lteSnrIndex));
            Integer lteSignal = sig_cursor.isNull(lteSignalIndex) ? null : sig_cursor.getInt(lteSignalIndex);
            Integer lteCqi = sig_cursor.isNull(lteCqiIndex) ? null : sig_cursor.getInt(lteCqiIndex);
            Integer rsrq = sig_cursor.isNull(rsrqIndex) ? null : sig_cursor.getInt(rsrqIndex);
            Integer eci0 = sig_cursor.isNull(ecioIndex) ? null : sig_cursor.getInt(ecioIndex);
            Integer ecn0 = sig_cursor.isNull(ecnoIndex) ? null : sig_cursor.getInt(ecnoIndex);
            Integer snr = sig_cursor.isNull(snrIndex) ? null : sig_cursor.getInt(snrIndex);
            Integer ber = sig_cursor.isNull(berIndex) ? null : sig_cursor.getInt(berIndex);
            Integer rscp = sig_cursor.isNull(rscpIndex) ? null : sig_cursor.getInt(rscpIndex);

            if (eci0 != null && (netType.equals("cdma") || netType.equals("lte")) && eci0 <= -30)
                eci0 = (eci0 / 10);
            else if (ecn0 != null && ecn0 > 1 && ecn0 < 60 && netType.equals("gsm"))
                ecn0 = -(ecn0 / 2);
            else if (eci0 != null && eci0 > 1 && eci0 < 60 && netType.equals("gsm"))
                eci0 = -(eci0 / 2);

            // if (lteSnr != null && lteSnr > 1 && lteSnr < 500)
            // lteSnr = (lteSnr+5)/10;
            if (lteSignal != null && lteSignal > -120 && lteSignal < -20) // rssi == lteSignal)
            {
                LTE_RSSI = simpleValidate(lteSignal);
                RSSI = 0;
            } else if (rssi == null || rssi == -255)
                RSSI = 0;
            else if (rssi == -256)
                RSSI = -256;
            else {
                String name = "RSCP: ";
                int spacing = 15;
                if (netType.equals("gsm") && (tier == 3 || tier == 4)) {
                    RSCP = rssi;
                    RSSI = 0;
                } else {
                    RSSI = rssi;
                    RSCP = 0;
                }

                LTE_RSSI = 0;
            }
            if (netType.equals("cdma") && rssi2G != null && rssi2G < -30 && rssi2G >= -120)
                CDMA_RSSI = rssi2G;
            if (tier == 5) {
                if (lteSnr != null && lteSnr > -101)
                    lteSnr = lteSnr / 10;
                if (rsrq != null && rsrq > 0)
                    rsrq = -rsrq;
                LTE_RSRP = simpleValidate(rsrp);
                LTE_RSRQ = simpleValidate(rsrq);
                LTE_SNR = simpleValidate(lteSnr);
                LTE_CQI = simpleValidate(lteCqi);
                ECIO = simpleValidate(eci0);
                ECNO = simpleValidate(ecn0);
            }
            //nerdview.setValue(0, "RSCP", simpleValidate(rscp, "RSCP", "dBm"));
            //BER = simpleValidate(ber);
            SNR = simpleValidate(snr);

            if (rsrp != null && rsrp <= -10 && rsrp >= -140 && tier == 5) {
                LTEIdentity = ReportManager.getInstance(context.getApplicationContext()).getNeighbors();
            } else {
                LTEIdentity = null;
                Neighbors = ReportManager.getInstance(context.getApplicationContext()).getNeighbors();
            }
        }
        location = ReportManager.getInstance(context.getApplicationContext()).getLastKnownLocation();

        try {
            JSONObject serviceMode = PhoneState.getServiceMode();
            if (serviceMode != null && serviceMode.getLong("time") + 5000 > System.currentTimeMillis()) {
                if (serviceMode.has("rrc") && serviceMode.getString("rrc").length() > 1) {
                    RRC = serviceMode.getString("rrc");
                } else
                    RRC = null;
                if (serviceMode.has("band") && serviceMode.getString("band").length() > 0) {
                    Band = Integer.parseInt(serviceMode.getString("band"));
                }
                //else
                if (serviceMode.has("freq") && serviceMode.getString("freq").length() > 0) {
                    Band = Integer.parseInt(serviceMode.getString("freq"));
                } else
                    Band = 0;
                if (serviceMode.has("channel") && serviceMode.getString("channel").length() > 0) {
                    Channel = Integer.parseInt(serviceMode.getString("channel"));
                } else
                    Channel = 0;
            } else {
                RRC = null;
                Band = 0;
                Channel = 0;
            }

            TelephonyManager telephonyManager = (TelephonyManager) context
                    .getSystemService(Service.TELEPHONY_SERVICE);
            String carrier = telephonyManager.getNetworkOperatorName();
            String mcc = "0", mnc = "0";
            if (telephonyManager.getNetworkOperator() != null
                    && telephonyManager.getNetworkOperator().length() >= 4) {
                mcc = telephonyManager.getNetworkOperator().substring(0, 3);
                mnc = telephonyManager.getNetworkOperator().substring(3);
            }
            int networkType = telephonyManager.getNetworkType();
            int networkTier = PhoneState.getNetworkGeneration(networkType);
            String nettype = PhoneState.getNetworkName(telephonyManager.getNetworkType());
            String data = PhoneState.getNetworkName(telephonyManager.getNetworkType()) + " ";
            int dataState = telephonyManager.getDataState();
            if (dataState == TelephonyManager.DATA_CONNECTED) {
                String activity = getActivityName(telephonyManager.getDataActivity());
                data += activity;
            } else if (telephonyManager.getNetworkType() != TelephonyManager.NETWORK_TYPE_UNKNOWN) {
                String state = getStateName(telephonyManager.getDataState());
                data += state;
            }

            Data = data;
            Carrier = carrier;

            Date date = new Date(System.currentTimeMillis());
            final String dateStr = DateFormat.getDateFormat(context).format(date);
            final String timeStr = dateStr + "  " + DateFormat.getTimeFormat(context).format(date);

            Time = timeStr;

            MCC = Integer.parseInt(mcc);
            MNC = Integer.parseInt(mnc);

            // Tell the service we're watching the signal, so keep it updated
            Intent intent = new Intent(CommonIntentActionsOld.VIEWING_SIGNAL);
            context.sendBroadcast(intent);

            WifiInfo wifiinfo = getWifiInfo();
            WifiConfiguration wifiConfig = getWifiConfig();
            setWifi(wifiinfo, wifiConfig);

            // Instantiate only the relevant Network type
            if (netType.equals("cdma"))
                connectedNetwork = CDMAInfo = new CDMAInfo(this);
            else if (netType.equals("gsm") && networkTier < 3)
                connectedNetwork = GSMInfo = new GSMInfo(this);
            else if (netType.equals("gsm") && networkTier < 5)
                connectedNetwork = WCDMAInfo = new WCDMAInfo(this);
            if (networkTier == 5) // LTE
                connectedNetwork = LTEInfo = new LTEInfo(this);
            if (wifiConfig != null)
                connectedNetwork = WiFiInfo = new WIFIInfo(this); // The most relevant network ends up in NetworkInfo
        } catch (Exception e) {
        }

    } catch (Exception e) {
        LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "updateNerdViewFromDB",
                "exception querying signal data: " + e.getMessage());
    } finally {
        if (cell_cursor != null)
            cell_cursor.close();
        if (sig_cursor != null)
            sig_cursor.close();
    }
}

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.j  a va  2s.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.tapjoy.TapjoyConnectCore.java

/**
 * Initialize data from the device information and application info.
 * This data is used in our URL connection to the Tapjoy server. 
 *//*from  ww  w .  j  a v  a 2  s  .c  o m*/
private void init() {
    PackageManager manager = context.getPackageManager();

    try {
        // ANDROID_ID
        androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);

        // Get app version.
        PackageInfo packageInfo = manager.getPackageInfo(context.getPackageName(), 0);
        appVersion = packageInfo.versionName;

        // Device platform.  Same as device type.
        deviceType = TapjoyConstants.TJC_DEVICE_PLATFORM_TYPE;
        platformName = TapjoyConstants.TJC_DEVICE_PLATFORM_TYPE;

        // Get the device model.
        deviceModel = android.os.Build.MODEL;
        deviceManufacturer = android.os.Build.MANUFACTURER;

        // Get the Android OS Version.
        deviceOSVersion = android.os.Build.VERSION.RELEASE;

        // Get the device country and language code.
        deviceCountryCode = Locale.getDefault().getCountry();
        deviceLanguage = Locale.getDefault().getLanguage();

        // Tapjoy SDK Library version.
        libraryVersion = TapjoyConstants.TJC_LIBRARY_VERSION_NUMBER;

        SharedPreferences settings = context.getSharedPreferences(TapjoyConstants.TJC_PREFERENCE, 0);

        try {
            TelephonyManager telephonyManager = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);

            if (telephonyManager != null) {
                deviceID = telephonyManager.getDeviceId();

                carrierName = telephonyManager.getNetworkOperatorName();
                carrierCountryCode = telephonyManager.getNetworkCountryIso();

                // getNetworkOperator() returns MCC + MNC, so make sure it's 5 or 6 digits total.
                // MCC is 3 digits
                // MNC is 2 or 3 digits
                if (telephonyManager.getNetworkOperator() != null
                        && (telephonyManager.getNetworkOperator().length() == 5
                                || telephonyManager.getNetworkOperator().length() == 6)) {
                    mobileCountryCode = telephonyManager.getNetworkOperator().substring(0, 3);
                    mobileNetworkCode = telephonyManager.getNetworkOperator().substring(3);
                }
            }

            TapjoyLog.i(TAPJOY_CONNECT, "deviceID: " + deviceID);

            boolean invalidDeviceID = false;

            //----------------------------------------
            // Is the device ID null or empty?
            //----------------------------------------
            if (deviceID == null) {
                TapjoyLog.e(TAPJOY_CONNECT, "Device id is null.");
                invalidDeviceID = true;
            } else
            //----------------------------------------
            // Is this an emulator device ID?
            //----------------------------------------
            if (deviceID.length() == 0 || deviceID.equals("000000000000000") || deviceID.equals("0")) {
                TapjoyLog.e(TAPJOY_CONNECT, "Device id is empty or an emulator.");
                invalidDeviceID = true;
            }
            //----------------------------------------
            // Valid device ID.
            //----------------------------------------
            else {
                // Lower case the device ID.
                deviceID = deviceID.toLowerCase();
            }

            TapjoyLog.i(TAPJOY_CONNECT, "ANDROID SDK VERSION: " + android.os.Build.VERSION.SDK);

            // Is this at least Android 2.3+?
            // Then let's get the serial.
            if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 9) {
                TapjoyLog.i(TAPJOY_CONNECT, "TRYING TO GET SERIAL OF 2.3+ DEVICE...");

                // THIS CLASS IS ONLY LOADED FOR ANDROID 2.3+
                TapjoyHardwareUtil hardware = new TapjoyHardwareUtil();

                serialID = hardware.getSerial();

                // Is there no IMEI or MEID?
                if (invalidDeviceID) {
                    deviceID = serialID;
                }

                TapjoyLog.i(TAPJOY_CONNECT, "====================");
                TapjoyLog.i(TAPJOY_CONNECT, "SERIAL: deviceID: [" + deviceID + "]");
                TapjoyLog.i(TAPJOY_CONNECT, "====================");

                //----------------------------------------
                // Is the device ID null or empty?
                //----------------------------------------
                if (deviceID == null) {
                    TapjoyLog.e(TAPJOY_CONNECT, "SERIAL: Device id is null.");
                    invalidDeviceID = true;
                } else
                //----------------------------------------
                // Is this an emulator device ID?
                //----------------------------------------
                if (deviceID.length() == 0 || deviceID.equals("000000000000000") || deviceID.equals("0")
                        || deviceID.equals("unknown")) {
                    TapjoyLog.e(TAPJOY_CONNECT, "SERIAL: Device id is empty or an emulator.");
                    invalidDeviceID = true;
                }
                //----------------------------------------
                // Valid device ID.
                //----------------------------------------
                else {
                    // Lower case the device ID.
                    deviceID = deviceID.toLowerCase();
                    invalidDeviceID = false;
                }
            }

            // Is the device ID invalid?  This is probably an emulator or pre-production device.
            if (invalidDeviceID) {
                StringBuffer buff = new StringBuffer();
                buff.append("EMULATOR");
                String deviceId = settings.getString(TapjoyConstants.PREF_EMULATOR_DEVICE_ID, null);

                // Do we already have an emulator device id stored for this device?
                if (deviceId != null && !deviceId.equals("")) {
                    deviceID = deviceId;
                }
                // Otherwise generate a deviceID for emulator testing.
                else {
                    String constantChars = "1234567890abcdefghijklmnopqrstuvw";

                    for (int i = 0; i < 32; i++) {
                        int randomChar = (int) (Math.random() * 100);
                        int ch = randomChar % 30;
                        buff.append(constantChars.charAt(ch));
                    }

                    deviceID = buff.toString().toLowerCase();

                    // Save the emulator device ID in the prefs so we can reuse it.
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString(TapjoyConstants.PREF_EMULATOR_DEVICE_ID, deviceID);
                    editor.commit();
                }
            }
        } catch (Exception e) {
            TapjoyLog.e(TAPJOY_CONNECT, "Error getting deviceID. e: " + e.toString());
            deviceID = null;
        }

        // Set the userID to the deviceID as the initial value.
        if (userID.length() == 0)
            userID = deviceID;

        // Save the SHA-2 hash of the device id.
        sha2DeviceID = TapjoyUtil.SHA256(deviceID);

        // Get screen density, dimensions and layout.
        try {
            // This is a backwards compatibility fix for Android 1.5 which has no display metric API.
            // If this is 1.6 or higher, then load the class, otherwise the class never loads and
            // no crash occurs.
            if (Integer.parseInt(android.os.Build.VERSION.SDK) > 3) {
                TapjoyDisplayMetricsUtil displayMetricsUtil = new TapjoyDisplayMetricsUtil(context);

                deviceScreenDensity = "" + displayMetricsUtil.getScreenDensity();
                deviceScreenLayoutSize = "" + displayMetricsUtil.getScreenLayoutSize();
            }
        } catch (Exception e) {
            TapjoyLog.e(TAPJOY_CONNECT, "Error getting screen density/dimensions/layout: " + e.toString());
        }

        // Get mac address.
        try {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

            if (wifiManager != null) {
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();

                if (wifiInfo != null) {
                    macAddress = wifiInfo.getMacAddress();

                    if (macAddress != null && macAddress.length() > 0) {
                        macAddress = macAddress.toUpperCase();
                        sha1MacAddress = TapjoyUtil.SHA1(macAddress);
                    }
                }
            }
        } catch (Exception e) {
            TapjoyLog.e(TAPJOY_CONNECT, "Error getting device mac address: " + e.toString());
        }

        // Alternate market.
        if (getFlagValue(TapjoyConnectFlag.ALTERNATE_MARKET) != null) {
            marketName = getFlagValue(TapjoyConnectFlag.ALTERNATE_MARKET);

            // Check for existing/supported market names.
            ArrayList<String> supportedMarketNames = new ArrayList<String>();
            supportedMarketNames.add(TapjoyConnectFlag.MARKET_GFAN);

            // Warning for undefined market names.
            if (!supportedMarketNames.contains(marketName)) {
                Log.w(TAPJOY_CONNECT, "Warning -- undefined ALTERNATE_MARKET: " + marketName);
            }
        }

        // Get the referral URL
        String tempReferralURL = settings.getString(TapjoyConstants.PREF_REFERRAL_URL, null);
        if (tempReferralURL != null && !tempReferralURL.equals(""))
            referralURL = tempReferralURL;

        // Get the client package name.
        clientPackage = context.getPackageName();

        TapjoyLog.i(TAPJOY_CONNECT, "Metadata successfully loaded");

        TapjoyLog.i(TAPJOY_CONNECT, "APP_ID = [" + appID + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "ANDROID_ID: [" + androidID + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "CLIENT_PACKAGE = [" + clientPackage + "]");

        TapjoyLog.i(TAPJOY_CONNECT, "deviceID: [" + deviceID + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "sha2DeviceID: [" + sha2DeviceID + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "" + TapjoyConstants.TJC_DEVICE_SERIAL_ID + ": [" + serialID + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "" + TapjoyConstants.TJC_DEVICE_MAC_ADDRESS + ": [" + macAddress + "]");
        TapjoyLog.i(TAPJOY_CONNECT,
                "" + TapjoyConstants.TJC_DEVICE_SHA1_MAC_ADDRESS + ": [" + sha1MacAddress + "]");

        TapjoyLog.i(TAPJOY_CONNECT, "deviceName: [" + deviceModel + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "deviceManufacturer: [" + deviceManufacturer + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "deviceType: [" + deviceType + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "libraryVersion: [" + libraryVersion + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "deviceOSVersion: [" + deviceOSVersion + "]");

        TapjoyLog.i(TAPJOY_CONNECT, "COUNTRY_CODE: [" + deviceCountryCode + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "LANGUAGE_CODE: [" + deviceLanguage + "]");

        TapjoyLog.i(TAPJOY_CONNECT, "density: [" + deviceScreenDensity + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "screen_layout: [" + deviceScreenLayoutSize + "]");

        TapjoyLog.i(TAPJOY_CONNECT, "carrier_name: [" + carrierName + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "carrier_country_code: [" + carrierCountryCode + "]");
        TapjoyLog.i(TAPJOY_CONNECT,
                "" + TapjoyConstants.TJC_MOBILE_COUNTRY_CODE + ": [" + mobileCountryCode + "]");
        TapjoyLog.i(TAPJOY_CONNECT,
                "" + TapjoyConstants.TJC_MOBILE_NETWORK_CODE + ": [" + mobileNetworkCode + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "" + TapjoyConstants.TJC_MARKET_NAME + ": [" + marketName + "]");

        TapjoyLog.i(TAPJOY_CONNECT, "referralURL: [" + referralURL + "]");

        if (connectFlags != null) {
            TapjoyLog.i(TAPJOY_CONNECT, "Connect Flags:");
            TapjoyLog.i(TAPJOY_CONNECT, "--------------------");

            Set<Entry<String, String>> entries = connectFlags.entrySet();
            Iterator<Entry<String, String>> iterator = entries.iterator();

            while (iterator.hasNext()) {
                Entry<String, String> item = iterator.next();
                TapjoyLog.i(TAPJOY_CONNECT,
                        "key: " + item.getKey() + ", value: " + Uri.encode(item.getValue()));
            }
        }
    } catch (Exception e) {
        TapjoyLog.e(TAPJOY_CONNECT, "Error initializing Tapjoy parameters.  e=" + e.toString());
    }
}

From source file:net.kidlogger.kidlogger.KLService.java

public void runRoamingEvent() {
    new Thread(new Runnable() {
        public void run() {
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            try {
                String country = tm.getNetworkCountryIso();
                String operator = tm.getNetworkOperatorName();
                sync.writeLog(".htm", Templates.getRoamingInfo(country.toUpperCase(Locale.US), operator));
            } catch (Exception e) {
                app.logError(CN + "runRoamingEvent", e.toString());
            }//www .j  av a  2  s . c om
        }
    }).start();
}

From source file:uk.bowdlerize.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    switch (item.getItemId()) {
    case R.id.action_add: {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // Get the layout inflater
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_add_url, null);

        final EditText urlET = (EditText) dialogView.findViewById(R.id.urlET);

        builder.setView(dialogView)/*from w  w  w.  j  av  a  2s  .co  m*/
                .setPositiveButton(R.string.action_add, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        Bundle extras = new Bundle();
                        Intent receiveURLIntent = new Intent(MainActivity.this, CensorCensusService.class);

                        extras.putString("url", urlET.getText().toString());
                        extras.putString("hash", MD5(urlET.getText().toString()));
                        extras.putInt("urgency", 0);
                        extras.putBoolean("local", true);

                        //Add our extra info
                        if (getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE)
                                .getBoolean("sendISPMeta", true)) {
                            WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
                            TelephonyManager telephonyManager = ((TelephonyManager) getSystemService(
                                    Context.TELEPHONY_SERVICE));

                            if (wifiMgr.isWifiEnabled() && null != wifiInfo.getSSID()) {
                                LocalCache lc = null;
                                Pair<Boolean, String> seenBefore = null;
                                try {
                                    lc = new LocalCache(MainActivity.this);
                                    lc.open();
                                    seenBefore = lc.findSSID(wifiInfo.getSSID().replaceAll("\"", ""));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                if (null != lc)
                                    lc.close();

                                if (seenBefore.first) {
                                    extras.putString("isp", seenBefore.second);
                                } else {
                                    extras.putString("isp", "unknown");
                                }

                                try {
                                    extras.putString("sim", telephonyManager.getSimOperatorName());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                try {
                                    extras.putString("isp", telephonyManager.getNetworkOperatorName());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                try {
                                    extras.putString("sim", telephonyManager.getSimOperatorName());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                        receiveURLIntent.putExtras(extras);
                        startService(receiveURLIntent);
                        dialog.cancel();
                    }
                }).setNegativeButton(R.string.action_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        builder.show();
        return true;
    }
    }
    return super.onOptionsItemSelected(item);
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
* Gets the network carrier./*from w  ww.jav  a  2 s  . c o m*/
*
* If the device is an emulator returns "EMU", if no SIM is present returns
* NOSIM.
*
* @See NETWORK_PROVIDER.
*
* @param ctx
* @return
*/
public static NETWORK_PROVIDER net_getCurrentNetworkOperator(Context ctx) {
    final String emulatorDevice = "Android";
    final String noSIMDevice = "";

    // if(Debug.isDebuggerConnected()){}

    TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
    String networkOperator = tm.getNetworkOperatorName();
    if (emulatorDevice.equalsIgnoreCase(networkOperator)) {
        return NETWORK_PROVIDER.EMU;
    } else if (emulatorDevice.equalsIgnoreCase(noSIMDevice)) {
        return NETWORK_PROVIDER.NOSIM;
    } else {
        try {
            return NETWORK_PROVIDER.valueOf(networkOperator.toUpperCase());
        } catch (Exception e) {
            // Non expected network provider.
            return NETWORK_PROVIDER.UNKNOWN;
        }
    }
}