Example usage for android.net NetworkInfo getTypeName

List of usage examples for android.net NetworkInfo getTypeName

Introduction

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

Prototype

@Deprecated
public String getTypeName() 

Source Link

Document

Return a human-readable name describe the type of the network, for example "WIFI" or "MOBILE".

Usage

From source file:com.vonglasow.michael.satstat.GpsEventReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);

    // some logic to use the pre-1.7 setting KEY_PREF_UPDATE_WIFI as a
    // fallback if KEY_PREF_UPDATE_NETWORKS is not set
    Set<String> fallbackUpdateNetworks = new HashSet<String>();
    if (sharedPref.getBoolean(Const.KEY_PREF_UPDATE_WIFI, false)) {
        fallbackUpdateNetworks.add(Const.KEY_PREF_UPDATE_NETWORKS_WIFI);
    }/*from  w w w. ja  va  2s .c  o m*/
    Set<String> updateNetworks = sharedPref.getStringSet(Const.KEY_PREF_UPDATE_NETWORKS,
            fallbackUpdateNetworks);

    if (intent.getAction().equals(Const.GPS_ENABLED_CHANGE)
            || intent.getAction().equals(Const.GPS_ENABLED_CHANGE)) {
        //FIXME: why are we checking for the same intent twice? Should on of them be GPS_FIX_CHANGE?
        // an application has connected to GPS or disconnected from it, check if notification needs updating
        boolean notifyFix = sharedPref.getBoolean(Const.KEY_PREF_NOTIFY_FIX, false);
        boolean notifySearch = sharedPref.getBoolean(Const.KEY_PREF_NOTIFY_SEARCH, false);
        if (notifyFix || notifySearch) {
            boolean isRunning = false;
            ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                if (PasvLocListenerService.class.getName().equals(service.service.getClassName())) {
                    isRunning = true;
                }
            }
            if (!isRunning) {
                Intent startServiceIntent = new Intent(context, PasvLocListenerService.class);
                startServiceIntent.setAction(intent.getAction());
                startServiceIntent.putExtras(intent.getExtras());
                context.startService(startServiceIntent);
            }
        }
    } else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)
            && updateNetworks.contains(Const.KEY_PREF_UPDATE_NETWORKS_WIFI)) {
        // change in WiFi connectivity, check if we are connected and need to refresh AGPS
        //FIXME: KEY_PREF_UPDATE_WIFI as fallback only
        NetworkInfo netinfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
        if (netinfo == null)
            return;
        if (!netinfo.isConnected())
            return;
        //Toast.makeText(context, "WiFi is connected", Toast.LENGTH_SHORT).show();
        Log.i(this.getClass().getSimpleName(), "WiFi is connected");
        refreshAgps(context, true, false);
    } else if ((intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION))
            || (intent.getAction().equals(Const.AGPS_DATA_EXPIRED))) {
        // change in network connectivity or AGPS expiration timer fired
        boolean isAgpsExpired = false;
        if (intent.getAction().equals(Const.AGPS_DATA_EXPIRED)) {
            Log.i(this.getClass().getSimpleName(), "AGPS data expired, checking available networks");
            isAgpsExpired = true;
        }
        NetworkInfo netinfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE))
                .getActiveNetworkInfo();
        if (netinfo == null)
            return;
        if (!netinfo.isConnected())
            return;
        String type;
        if ((netinfo.getType() < ConnectivityManager.TYPE_MOBILE_MMS)
                || (netinfo.getType() > ConnectivityManager.TYPE_MOBILE_HIPRI)) {
            type = Integer.toString(netinfo.getType());
        } else {
            // specific mobile data connections will be treated as TYPE_MOBILE
            type = Const.KEY_PREF_UPDATE_NETWORKS_MOBILE;
        }
        if (!updateNetworks.contains(type))
            return;
        if (!isAgpsExpired)
            Log.i(this.getClass().getSimpleName(),
                    "Network of type " + netinfo.getTypeName() + " is connected");
        // Enforce the update interval if we were called by a network event
        // but not if we were called by a timer, because in that case the
        // check has already been done. (I am somewhat paranoid and don't
        // count on alarms not going off a few milliseconds too early.)
        refreshAgps(context, !isAgpsExpired, false);
    }
}

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   ww w  . ja  va 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.newsrob.EntryManager.java

public boolean isNetworkConnected(Context ctx) {

    if (connectivityManager == null)
        connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
    if (ni == null) {
        PL.log("EntryManager. Wasn't able to get NI.", ctx);
        return false;
    }/* www  . j  a  v  a  2s .c  o m*/

    if (NewsRob.isDebuggingEnabled(ctx)) {
        PL.log("ActiveNetwork: " + ni.getTypeName(), ctx);
        PL.log("ActiveNetworkState: " + ni.getDetailedState(), ctx);
        PL.log("isNetworkConnected? " + ni.isConnected(), ctx);
    }

    return ni.isConnected();
}

From source file:com.grazerss.EntryManager.java

public boolean isNetworkConnected(Context ctx) {

    if (connectivityManager == null) {
        connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    }//from ww  w .j a va 2 s. c  om

    NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
    if (ni == null) {
        PL.log("EntryManager. Wasn't able to get NI.", ctx);
        return false;
    }

    if (NewsRob.isDebuggingEnabled(ctx)) {
        PL.log("ActiveNetwork: " + ni.getTypeName(), ctx);
        PL.log("ActiveNetworkState: " + ni.getDetailedState(), ctx);
        PL.log("isNetworkConnected? " + ni.isConnected(), ctx);
    }

    return ni.isConnected();
}

From source file:com.irccloud.android.NetworkConnection.java

@SuppressWarnings("deprecation")
public NetworkConnection() {
    String version;/*from  w  ww  .  j a  va 2 s .co  m*/
    String network_type = null;
    try {
        version = "/" + IRCCloudApplication.getInstance().getPackageManager().getPackageInfo(
                IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), 0).versionName;
    } catch (Exception e) {
        version = "";
    }

    try {
        ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null)
            network_type = ni.getTypeName();
    } catch (Exception e) {
    }

    try {
        config = new JSONObject(PreferenceManager
                .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext())
                .getString("config", "{}"));
    } catch (JSONException e) {
        e.printStackTrace();
        config = new JSONObject();
    }

    useragent = "IRCCloud" + version + " (" + android.os.Build.MODEL + "; "
            + Locale.getDefault().getCountry().toLowerCase() + "; " + "Android "
            + android.os.Build.VERSION.RELEASE;

    WindowManager wm = (WindowManager) IRCCloudApplication.getInstance()
            .getSystemService(Context.WINDOW_SERVICE);
    useragent += "; " + wm.getDefaultDisplay().getWidth() + "x" + wm.getDefaultDisplay().getHeight();

    if (network_type != null)
        useragent += "; " + network_type;

    useragent += ")";

    WifiManager wfm = (WifiManager) IRCCloudApplication.getInstance().getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);
    wifiLock = wfm.createWifiLock(TAG);

    kms = new X509ExtendedKeyManager[1];
    kms[0] = new X509ExtendedKeyManager() {
        @Override
        public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) {
            return SSLAuthAlias;
        }

        @Override
        public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
            throw new UnsupportedOperationException();
        }

        @Override
        public X509Certificate[] getCertificateChain(String alias) {
            return SSLAuthCertificateChain;
        }

        @Override
        public String[] getClientAliases(String keyType, Principal[] issuers) {
            throw new UnsupportedOperationException();
        }

        @Override
        public String[] getServerAliases(String keyType, Principal[] issuers) {
            throw new UnsupportedOperationException();
        }

        @Override
        public PrivateKey getPrivateKey(String alias) {
            return SSLAuthKey;
        }
    };

    tms = new TrustManager[1];
    tms[0] = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            throw new CertificateException("Not implemented");
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
                trustManagerFactory.init((KeyStore) null);

                for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
                    if (trustManager instanceof X509TrustManager) {
                        X509TrustManager x509TrustManager = (X509TrustManager) trustManager;
                        x509TrustManager.checkServerTrusted(chain, authType);
                    }
                }
            } catch (KeyStoreException e) {
                throw new CertificateException(e);
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException(e);
            }

            if (BuildConfig.SSL_FPS != null && BuildConfig.SSL_FPS.length > 0) {
                try {
                    MessageDigest md = MessageDigest.getInstance("SHA-1");
                    byte[] sha1 = md.digest(chain[0].getEncoded());
                    // http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java
                    final char[] hexArray = "0123456789ABCDEF".toCharArray();
                    char[] hexChars = new char[sha1.length * 2];
                    for (int j = 0; j < sha1.length; j++) {
                        int v = sha1[j] & 0xFF;
                        hexChars[j * 2] = hexArray[v >>> 4];
                        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
                    }
                    String hexCharsStr = new String(hexChars);
                    boolean matched = false;
                    for (String fp : BuildConfig.SSL_FPS) {
                        if (fp.equals(hexCharsStr)) {
                            matched = true;
                            break;
                        }
                    }
                    if (!matched)
                        throw new CertificateException("Incorrect CN in cert chain");
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    WebSocketClient.setTrustManagers(tms);
}

From source file:org.openhab.habdroid.ui.OpenHABWidgetListActivity.java

/**
 * This is called when activity is created. Initializes the state, performs network
 * state based selection for app initialization and starts the widget list
 *//*w  w w  . j  av a  2  s. co  m*/
@Override
public void onCreate(Bundle savedInstanceState) {
    Log.d("OpenHABWidgetListActivity", "onCreate");
    // Set default values, false means do it one time during the very first launch
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    // Set non-persistant HABDroid version preference to current version from application package
    try {
        PreferenceManager.getDefaultSharedPreferences(this).edit().putString("default_openhab_appversion",
                getPackageManager().getPackageInfo(getPackageName(), 0).versionName).commit();
    } catch (NameNotFoundException e1) {
        if (e1 != null)
            Log.d(TAG, e1.getMessage());
    }
    // Set the theme to one from preferences
    Util.setActivityTheme(this);
    // Fetch openHAB service type name from strings.xml
    openHABServiceType = getString(R.string.openhab_service_type);
    // Enable progress ring bar
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    requestWindowFeature(Window.FEATURE_PROGRESS);
    setProgressBarIndeterminateVisibility(true);
    // Initialize crittercism reporting
    JSONObject crittercismConfig = new JSONObject();
    try {
        crittercismConfig.put("shouldCollectLogcat", true);
    } catch (JSONException e) {
        if (e.getMessage() != null)
            Log.e(TAG, e.getMessage());
        else
            Log.e(TAG, "Crittercism JSON exception");
    }
    Crittercism.init(getApplicationContext(), "5117659f59e1bd4ba9000004", crittercismConfig);
    // Initialize activity view
    super.onCreate(savedInstanceState);
    setContentView(R.layout.openhabwidgetlist);
    // Disable screen timeout if set in preferences
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    if (settings.getBoolean("default_openhab_screentimeroff", false)) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
    // Check if we got all needed permissions
    PackageManager pm = getPackageManager();
    if (!(pm.checkPermission(permission.CHANGE_WIFI_MULTICAST_STATE,
            getPackageName()) == PackageManager.PERMISSION_GRANTED)) {
        showAlertDialog(getString(R.string.erorr_no_wifi_mcast_permission));
        serviceDiscoveryEnabled = false;
    }
    if (!(pm.checkPermission(permission.ACCESS_WIFI_STATE,
            getPackageName()) == PackageManager.PERMISSION_GRANTED)) {
        showAlertDialog(getString(R.string.erorr_no_wifi_state_permission));
        serviceDiscoveryEnabled = false;
    }
    // Get username/password from preferences
    openHABUsername = settings.getString("default_openhab_username", null);
    openHABPassword = settings.getString("default_openhab_password", null);
    // Create new data source and adapter and set it to list view
    openHABWidgetDataSource = new OpenHABWidgetDataSource();
    openHABWidgetAdapter = new OpenHABWidgetAdapter(OpenHABWidgetListActivity.this,
            R.layout.openhabwidgetlist_genericitem, widgetList);
    getListView().setAdapter(openHABWidgetAdapter);
    // Set adapter parameters
    openHABWidgetAdapter.setOpenHABUsername(openHABUsername);
    openHABWidgetAdapter.setOpenHABPassword(openHABPassword);
    // Enable app logo as home button
    this.getActionBar().setHomeButtonEnabled(true);
    // Check if we have openHAB page url in saved instance state?
    if (savedInstanceState != null) {
        displayPageUrl = savedInstanceState.getString("displayPageUrl");
        openHABBaseUrl = savedInstanceState.getString("openHABBaseUrl");
        sitemapRootUrl = savedInstanceState.getString("sitemapRootUrl");
        openHABWidgetAdapter.setOpenHABBaseUrl(openHABBaseUrl);
    }
    // Check if this is a launch from myself (drill down navigation)
    if (getIntent() != null) {
        if (getIntent().getAction() != null) {
            if (getIntent().getAction().equals("org.openhab.habdroid.ui.OpwnHABWidgetListActivity")) {
                displayPageUrl = getIntent().getExtras().getString("displayPageUrl");
                openHABBaseUrl = getIntent().getExtras().getString("openHABBaseUrl");
                sitemapRootUrl = getIntent().getExtras().getString("sitemapRootUrl");
                this.setTitle(getIntent().getExtras().getString("pageTitle"));
                openHABWidgetAdapter.setOpenHABBaseUrl(openHABBaseUrl);
            }
        }
    }
    // If yes, then just go to it (means restore activity from it's saved state)
    if (displayPageUrl.length() > 0) {
        Log.d(TAG, "displayPageUrl = " + displayPageUrl);
        showPage(displayPageUrl, false);
        // If not means it is a clean start
    } else {
        if (getIntent() != null) {
            Log.i(TAG, "Launch intent = " + getIntent().getAction());
            // If this is a launch through NFC tag reading
            if (getIntent().getAction() != null) {
                if (getIntent().getAction().equals("android.nfc.action.NDEF_DISCOVERED")) {
                    // Save url which we got from NFC tag
                    nfcTagData = getIntent().getDataString();
                }
            }
        }
        // If we are in demo mode, ignore all settings and use demo url from strings
        if (settings.getBoolean("default_openhab_demomode", false)) {
            openHABBaseUrl = getString(R.string.openhab_demo_url);
            Log.i(TAG, "Demo mode, connecting to " + openHABBaseUrl);
            Toast.makeText(getApplicationContext(), getString(R.string.info_demo_mode), Toast.LENGTH_LONG)
                    .show();
            showTime();
        } else {
            openHABBaseUrl = normalizeUrl(settings.getString("default_openhab_url", ""));
            // Check if we have a direct URL in preferences, if yes - use it
            if (openHABBaseUrl.length() > 0) {
                Log.i(TAG, "Connecting to configured URL = " + openHABBaseUrl);
                Toast.makeText(getApplicationContext(), getString(R.string.info_conn_url), Toast.LENGTH_SHORT)
                        .show();
                showTime();
            } else {
                // Get current network information
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
                        Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                if (activeNetworkInfo != null) {
                    Log.i(TAG, "Network is connected");
                    // If network is mobile, try to use remote URL
                    if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE
                            || serviceDiscoveryEnabled == false) {
                        if (!serviceDiscoveryEnabled) {
                            Log.i(TAG, "openHAB discovery is disabled");
                        } else {
                            Log.i(TAG, "Network is Mobile (" + activeNetworkInfo.getSubtypeName() + ")");
                        }
                        openHABBaseUrl = normalizeUrl(settings.getString("default_openhab_alturl", ""));
                        // If remote URL is configured
                        if (openHABBaseUrl.length() > 0) {
                            Toast.makeText(getApplicationContext(), getString(R.string.info_conn_rem_url),
                                    Toast.LENGTH_SHORT).show();
                            Log.i(TAG, "Connecting to remote URL " + openHABBaseUrl);
                            showTime();
                        } else {
                            Toast.makeText(getApplicationContext(), getString(R.string.error_no_url),
                                    Toast.LENGTH_LONG).show();
                        }
                        // If network is WiFi or Ethernet
                    }
                    if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI
                            || activeNetworkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                        Log.i(TAG, "Network is WiFi or Ethernet");
                        // Start service discovery
                        this.serviceResolver = new AsyncServiceResolver(this, openHABServiceType);
                        progressDialog = ProgressDialog.show(this, "", "Discovering openHAB. Please wait...",
                                true);
                        this.serviceResolver.start();
                        // We don't know how to handle this network type
                    } else {
                        Log.i(TAG, "Network type (" + activeNetworkInfo.getTypeName() + ") is unsupported");
                    }
                    // Network is not available
                } else {
                    Log.i(TAG, "Network is not available");
                    Toast.makeText(getApplicationContext(), getString(R.string.error_network_not_available),
                            Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

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;
    }/*  w ww.j  a v  a  2s  .  com*/
    String apName = info.getTypeName() + "_" + info.getSubtypeName();
    if (info.getExtraInfo() != null) {
        apName += "_" + info.getExtraInfo();
    }
    return apName;
}