Example usage for android.text.format Formatter formatIpAddress

List of usage examples for android.text.format Formatter formatIpAddress

Introduction

In this page you can find the example usage for android.text.format Formatter formatIpAddress.

Prototype

@Deprecated
public static String formatIpAddress(int ipv4Address) 

Source Link

Document

Returns a string in the canonical IPv4 format ###.###.###.### from a packed integer containing the IP address.

Usage

From source file:com.sitewhere.android.example.MainActivity.java

private Map<String, String> buildRegistrationMetadata() {
    Map<String, String> metadata = new HashMap<>();

    WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
    String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

    String reqString = Build.MANUFACTURER + " " + Build.MODEL + " " + Build.VERSION.RELEASE + " "
            + Build.VERSION_CODES.class.getFields()[android.os.Build.VERSION.SDK_INT].getName();

    metadata.put("ipaddress", ip);
    metadata.put("android.os.version", Build.VERSION.BASE_OS);
    metadata.put("android.os.description", reqString);

    return metadata;
}

From source file:com.sckftr.android.utils.net.Network.java

/**
 * Get IP address from first non-localhost interface
 * @return  address or empty string//from w w w .ja  v  a2s  .  c  o  m
 */
public static String getLocalIpAddress() {
    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()) {
                    String ip = Formatter.formatIpAddress(inetAddress.hashCode());
                    Log.i("NET", "***** IP=" + ip);
                    return ip;
                }
            }
        }
    } catch (SocketException ex) {
        Log.e("NET", ex.toString());
    }
    return null;
}

From source file:eu.intermodalics.tango_ros_streamer.RunningActivity.java

/**
 * This function initializes the tango ros node with RosJava interface.
 *//*from ww  w .ja  v a2  s. c o m*/
private void initAndStartRosJavaNode() {
    if (mRunLocalMaster) {
        this.nodeMainExecutorService.startMaster(/*isPrivate*/ false);
        mMasterUri = this.nodeMainExecutorService.getMasterUri().toString();
        // The URI returned by getMasterUri is correct but looks 'weird',
        // e.g. 'http://android-c90553518bc67cf5:1131'.
        // Instead of showing this to the user, we show the IP address of the device,
        // which is also correct and less confusing.
        WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        String deviceIP = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress());
        mUriTextView = (TextView) findViewById(R.id.master_uri);
        mUriTextView.setText("http://" + deviceIP + ":11311");
    }
    if (mMasterUri != null) {
        URI masterUri;
        try {
            masterUri = URI.create(mMasterUri);
        } catch (IllegalArgumentException e) {
            Log.e(TAG, "Wrong URI: " + e.getMessage());
            return;
        }
        this.nodeMainExecutorService.setMasterUri(masterUri);
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                RunningActivity.this.init(nodeMainExecutorService);
                return null;
            }
        }.execute();
    } else {
        Log.e(TAG, "Master URI is null");
    }
}

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

@SuppressLint("DefaultLocale")
private void updateConsole() {

    if (mSystemViews.isEmpty())
        return;//from   w  w  w. jav  a2 s  . c o  m

    try {
        // ----- System -----
        int threadCount = Thread.activeCount();
        ApplicationInfo appInfo = getActivity().getApplicationInfo();

        mSystemViews.get(SYSTEM_PACKAGE).get(1).setText(appInfo.packageName);
        mSystemViews.get(SYSTEM_MODEL).get(1).setText(Build.MODEL);
        mSystemViews.get(SYSTEM_ANDROID).get(1).setText(Build.VERSION.RELEASE);

        if (Build.VERSION.SDK_INT >= 16) {
            int lines = 0;
            final StringBuilder permSb = new StringBuilder();
            try {
                PackageInfo pi = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(),
                        PackageManager.GET_PERMISSIONS);
                for (int i = 0; i < pi.requestedPermissions.length; i++) {
                    if ((pi.requestedPermissionsFlags[i] & PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0) {
                        permSb.append(pi.requestedPermissions[i]).append("\n");
                        lines++;
                    }
                }
            } catch (Exception e) {
            }
            final int lineCnt = lines;
            mSystemViews.get(SYSTEM_PERM).get(1).setText(String.format("%d perms [press]", lines));
            mSystemViews.get(SYSTEM_PERM).get(1).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getTag() == null) {
                        String permStr = permSb.toString().replaceAll("android.permission.", "")
                                .replaceAll("\n[^\n]*permission", "");
                        mSystemViews.get(SYSTEM_PERM).get(1).setText(permStr);
                        mSystemViews.get(SYSTEM_PERM).get(0).setLines(lineCnt);
                        mSystemViews.get(SYSTEM_PERM).get(1).setLines(lineCnt);
                        mSystemViews.get(SYSTEM_PERM).get(1).setTag(lineCnt);
                    } else {
                        mSystemViews.get(SYSTEM_PERM).get(1).setText(String.format("%d perms", lineCnt));
                        mSystemViews.get(SYSTEM_PERM).get(0).setLines(1);
                        mSystemViews.get(SYSTEM_PERM).get(1).setLines(1);
                        mSystemViews.get(SYSTEM_PERM).get(1).setTag(null);
                    }
                }
            });

        } else {
            String permStr = "";
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                permStr += (" Find Loc");
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                permStr += (" Coarse Loc");
            mSystemViews.get(SYSTEM_PERM).get(1).setText(permStr);
        }

        ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        int processCnt = actMgr.getRunningAppProcesses().size();
        mSystemViews.get(SYSTEM_PROCESSES).get(1).setText(String.format("%d", consoleState.processCnt));
        mSystemViews.get(SYSTEM_PROCESSES).get(2).setText(String.format("%d", processCnt));
        // mSystemViews.get(SYSTEM_BATTERY).get(1).setText(String.format("%d%%", consoleState.batteryLevel));
        mSystemViews.get(SYSTEM_BATTERY).get(2)
                .setText(String.format("%%%d", calculateBatteryLevel(getActivity())));
        // long cpuNano = Debug.threadCpuTimeNanos();
        // mSystemViews.get(SYSTEM_CPU).get(2).setText(String.format("%d%%", cpuNano));

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        // ----- Network WiFi-----

        WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) {
            DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();
            mNetworkViews.get(NETWORK_WIFI_IP).get(1).setText(Formatter.formatIpAddress(dhcpInfo.ipAddress));
            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            mNetworkViews.get(NETWORK_WIFI_SPEED).get(1).setText(String.valueOf(wifiInfo.getLinkSpeed()));
            int numberOfLevels = 10;
            int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1);
            mNetworkViews.get(NETWORK_WIFI_SIGNAL).get(1)
                    .setText(String.format("%%%d", 100 * level / numberOfLevels));
        }
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
    try {
        // ----- Network Traffic-----
        // int uid = android.os.Process.myUid();
        mNetworkViews.get(NETWORK_RCV_BYTES).get(1).setText(String.format("%d", consoleState.netRxBytes));
        mNetworkViews.get(NETWORK_RCV_PACK).get(1).setText(String.format("%d", consoleState.netRxPacks));
        mNetworkViews.get(NETWORK_SND_BYTES).get(1).setText(String.format("%d", consoleState.netTxBytes));
        mNetworkViews.get(NETWORK_SND_PACK).get(1).setText(String.format("%d", consoleState.netTxPacks));

        mNetworkViews.get(NETWORK_RCV_BYTES).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxBytes()));
        mNetworkViews.get(NETWORK_RCV_PACK).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets()));
        mNetworkViews.get(NETWORK_SND_BYTES).get(2)
                .setText(String.format("%d", TrafficStats.getTotalTxBytes()));
        mNetworkViews.get(NETWORK_SND_PACK).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets()));

        mNetworkViews.get(NETWORK_RCV_BYTES).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxBytes() - consoleState.netRxBytes));
        mNetworkViews.get(NETWORK_RCV_PACK).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets() - consoleState.netRxPacks));
        mNetworkViews.get(NETWORK_SND_BYTES).get(3)
                .setText(String.format("%d", TrafficStats.getTotalTxBytes() - consoleState.netTxBytes));
        mNetworkViews.get(NETWORK_SND_PACK).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets() - consoleState.netTxPacks));

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // ----- Memory -----
    try {
        MemoryInfo mi = new MemoryInfo();
        ActivityManager activityManager = (ActivityManager) getActivity()
                .getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);

        long heapUsing = Debug.getNativeHeapSize();

        Date now = new Date();
        long deltaMsec = now.getTime() - consoleState.lastFreeze.getTime();

        List<TextView> timeViews = mMemoryViews.get(MEMORY_TIME);
        timeViews.get(1).setText(TIMEFORMAT.format(consoleState.lastFreeze));
        timeViews.get(2).setText(TIMEFORMAT.format(now));
        timeViews.get(3).setText(
                DateUtils.getRelativeTimeSpanString(consoleState.lastFreeze.getTime(), now.getTime(), 0));
        // timeViews.get(3).setText( String.valueOf(deltaMsec));

        List<TextView> usingViews = mMemoryViews.get(MEMORY_USING);
        usingViews.get(1).setText(String.format("%d", consoleState.usingMemory));
        usingViews.get(2).setText(String.format("%d", heapUsing));
        usingViews.get(3).setText(String.format("%d", heapUsing - consoleState.usingMemory));

        List<TextView> freeViews = mMemoryViews.get(MEMORY_FREE);
        freeViews.get(1).setText(String.format("%d", consoleState.freeMemory));
        freeViews.get(2).setText(String.format("%d", mi.availMem));
        freeViews.get(3).setText(String.format("%d", mi.availMem - consoleState.freeMemory));

        List<TextView> totalViews = mMemoryViews.get(MEMORY_TOTAL);
        if (Build.VERSION.SDK_INT >= 16) {
            totalViews.get(1).setText(String.format("%d", consoleState.totalMemory));
            totalViews.get(2).setText(String.format("%d", mi.totalMem));
            totalViews.get(3).setText(String.format("%d", mi.totalMem - consoleState.totalMemory));
        } else {
            totalViews.get(0).setVisibility(View.GONE);
            totalViews.get(1).setVisibility(View.GONE);
            totalViews.get(2).setVisibility(View.GONE);
        }
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
}

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();// 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.compal.wifitest.WifiTestCase.java

public boolean saveAPConfig(String mAPType) {
    WifiConfiguration wc = new WifiConfiguration();

    if (mAPType.equalsIgnoreCase(dWpa)) {
        wc.SSID = WpaAPSsid;//from   ww w .  j  a v  a  2  s.co  m
        wc.preSharedKey = WpaAPKey;
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        wc.priority = 40; //!!
    }
    if (mAPType.equalsIgnoreCase(dWep)) {
        wc.SSID = WepAPSsid;
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
        wc.wepKeys[0] = WepAPKey; //This is the WEP Password
        wc.wepTxKeyIndex = 0;
    }
    if (mAPType.equalsIgnoreCase(dWpa2)) {
        wc.SSID = Wpa2APSsid;
        wc.preSharedKey = Wpa2APKey;
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    }
    if (mAPType.equalsIgnoreCase(dShared)) {
        wc.SSID = SharedAPSsid;
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    }
    wc.hiddenSSID = true;
    wc.status = WifiConfiguration.Status.DISABLED;
    wc.priority = 41; //!!

    wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);

    //boolean res1 = mWifiManager.setWifiEnabled(true);
    int res = mWifiManager.addNetwork(wc);
    Log.i(tag, "add" + mAPType + "Network returned " + res);
    boolean es = mWifiManager.saveConfiguration();
    Log.i(tag, mAPType + " saveConfiguration returned " + es);
    boolean b = mWifiManager.enableNetwork(res, true);
    Log.i(tag, mAPType + " enableNetwork returned " + b);

    long startTime = System.currentTimeMillis();
    while ((System.currentTimeMillis() - startTime) < LONG_TIMEOUT * 5) {
        if (mWifiManager.getConnectionInfo().getSupplicantState()
                .equals((SupplicantState) SupplicantState.COMPLETED)
                && !Formatter.formatIpAddress(mWifiManager.getConnectionInfo().getIpAddress())
                        .equalsIgnoreCase("0.0.0.0")) {
            Log.i(tag, Formatter.formatIpAddress(mWifiManager.getConnectionInfo().getIpAddress()));
            Log.i(tag,
                    "getConnectionInfo().getSupplicantState().equals((SupplicantState) SupplicantState.COMPLETED)");
            Log.i(tag, "IP && supplicant state complete = true : " + mAPType);
            return true;
        }
        sleep(100);
    }
    Log.i(tag, "IP || supplicant state complete = false : " + mAPType);
    return false;

}

From source file:eu.intermodalics.tango_ros_streamer.activities.RunningActivity.java

/**
 * This function initializes the tango ros node with RosJava interface.
 *//*from  w  w w  .j av  a2  s  .c  o  m*/
private void initAndStartRosJavaNode() {
    this.nodeMainExecutorService.addListener(new NodeMainExecutorServiceListener() {
        @Override
        public void onShutdown(NodeMainExecutorService nodeMainExecutorService) {
            unbindFromTango();
            mLogger.saveLogToFile();
            // This ensures to kill the process started by the app.
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    });
    if (mRunLocalMaster) {
        try {
            this.nodeMainExecutorService.startMaster(/*isPrivate*/ false);
            mMasterUri = this.nodeMainExecutorService.getMasterUri().toString();
            // The URI returned by getMasterUri is correct but looks 'weird',
            // e.g. 'http://android-c90553518bc67cf5:1131'.
            // Instead of showing this to the user, we show the IP address of the device,
            // which is also correct and less confusing.
            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
            String deviceIP = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress());
            mUriTextView = (TextView) findViewById(R.id.master_uri);
            mUriTextView.setText("http://" + deviceIP + ":11311");
        } catch (RosRuntimeException e) {
            e.printStackTrace();
            Log.e(TAG, getString(R.string.local_master_error));
            displayToastMessage(R.string.local_master_error);
            return;
        }
    }
    if (mMasterUri != null) {
        URI masterUri;
        try {
            masterUri = URI.create(mMasterUri);
        } catch (IllegalArgumentException e) {
            Log.e(TAG, "Wrong URI: " + e.getMessage());
            return;
        }
        this.nodeMainExecutorService.setMasterUri(masterUri);
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                RunningActivity.this.init(nodeMainExecutorService);
                return null;
            }
        }.execute();
    } else {
        Log.e(TAG, "Master URI is null");
    }
}