Example usage for android.net.wifi WifiManager getScanResults

List of usage examples for android.net.wifi WifiManager getScanResults

Introduction

In this page you can find the example usage for android.net.wifi WifiManager getScanResults.

Prototype

public List<ScanResult> getScanResults() 

Source Link

Document

Return the results of the latest access point scan.

Usage

From source file:at.ac.uniklu.mobile.sportal.service.MutingService.java

private void mute(int alarmId) {
    Log.d(TAG, "mute()");

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_WAITING) {
        Log.d(TAG, "mute() blocked - waiting for a location update");
        return;// w  w  w .  j  av a 2  s  . c o  m
    }

    // check if phone is already muted by the user
    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    boolean isPhoneAlreadyMuted = audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL
            && !Preferences.isMutingPeriod(preferences);
    if (isPhoneAlreadyMuted) {
        Log.d(TAG, "phone is already muted, scheduling next mute");
        scheduleMute(true);
        return;
    }

    // load the current period from the db
    MutingPeriod mutingPeriod = null;
    Log.d(TAG, "muting period id: " + alarmId);
    if (DEBUG_WITH_FAKE_ALARMS) {
        mutingPeriod = new MutingPeriod();
        mutingPeriod.setId(-1);
        mutingPeriod.setBegin(System.currentTimeMillis());
        mutingPeriod.setEnd(mutingPeriod.getBegin() + 10000);
        mutingPeriod.setName("Fakeevent");
    } else {
        mutingPeriod = Studentportal.getStudentPortalDB().mutingPeriods_getPeriod(alarmId);
    }

    // check if phone is located at university
    notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(),
            getString(R.string.automute_notification_course_started_locating));
    boolean isPhoneLocationKnown = false;
    boolean isPhoneLocatedAtUniversity = false;
    String locationSource = null;

    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    if (wifiManager.isWifiEnabled()) {
        ScanResult scanResult = MutingUtils.findMutingWifiNetwork(wifiManager.getScanResults());
        if (scanResult != null) {
            Log.d(TAG, "phone located by wifi: " + scanResult.SSID);
            isPhoneLocationKnown = true;
            isPhoneLocatedAtUniversity = true;
            locationSource = "wifi (" + scanResult.SSID + ")";
        }
    }

    if (!isPhoneLocationKnown) {
        // phone location could not be determined by wifi, trying network location instead...
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            Intent locationIntent = new Intent("at.ac.uniklu.mobile.sportal.LOCATION_UPDATE")
                    .putExtra(EXTRA_ALARM_ID, alarmId);
            PendingIntent pendingLocationIntent = PendingIntent.getBroadcast(this, 0, locationIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            // remove the location receiver (so it doesn't get registered multiple times [could also happen on overlapping mute() calls)
            locationManager.removeUpdates(pendingLocationIntent);

            if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_RECEIVED) {
                isPhoneLocationKnown = true;
                pendingLocationIntent.cancel();
                Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (location == null) {
                    Log.d(TAG, "location received but still null");
                } else {
                    MutingRegion mutingRegion = MutingUtils.findOverlappingMutingRegion(location);
                    if (mutingRegion != null) {
                        Log.d(TAG, "phone located by network @ " + mutingRegion.getName());
                        isPhoneLocatedAtUniversity = true;
                        locationSource = "location (" + mutingRegion.getName() + ")";
                    }
                }
            } else {
                Log.d(TAG, "trying to locate the phone by network...");
                // wait for a location update
                Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_WAITING);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                        pendingLocationIntent);
                return; // exit method - it will be re-called from the location broadcast receiver on a location update
            }
        }
    }

    boolean isAlwaysMuteEnabled = Preferences.isAutomuteWithoutLocation(this, preferences);

    if (isPhoneLocationKnown) {
        if (!isPhoneLocatedAtUniversity) {
            Log.d(TAG, "phone is not located at university, scheduling next mute");
            scheduleMute(true);
            removeNotification(Studentportal.NOTIFICATION_MS_INFO);
            return;
        }
    } else {
        Log.d(TAG, "phone cannot be located");
        if (!isAlwaysMuteEnabled) {
            Log.d(TAG, "alwaysmute is disabled, scheduling next mute");
            Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_NONE);
            scheduleMute(true);
            removeNotification(Studentportal.NOTIFICATION_MS_INFO);
            return;
        }
    }

    // only turn the ringtone off if we aren't currently in a muting period.
    // if we are in a muting period the ringtone is already muted and the request should be ignored,
    // else rintoneTurnOn() won't turn the ringtone back on because ringtone override will be set to true
    if (!Preferences.isMutingPeriod(preferences)) {
        MutingUtils.ringtoneTurnOff(this);
    }

    // persist that from now on the phone is in a muting period
    Preferences.setMutingPeriod(preferences, true);

    // inform user via a notification that a course has started and the phone has been muted
    notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(),
            getString(R.string.automute_notification_course_muted));

    final boolean isPhoneLocationKnownAnalytics = isPhoneLocationKnown;
    final String locationSourceAnalytics = locationSource;
    Analytics.onEvent(Analytics.EVENT_MUTINGSERVICE_MUTE, "isPhoneLocationKnown",
            isPhoneLocationKnownAnalytics + "", "locationSource", locationSourceAnalytics);

    scheduleUnmute(mutingPeriod.getEnd());
}

From source file:com.prey.PreyPhone.java

private void updateListWifi() {
    listWifi = new ArrayList<PreyPhone.Wifi>();

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || (ActivityCompat.checkSelfPermission(ctx,
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(ctx,
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
        WifiManager wifiMgr = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
        List<ScanResult> listScanResults = wifiMgr.getScanResults();
        for (int i = 0; listScanResults != null && i < listScanResults.size(); i++) {
            ScanResult scan = listScanResults.get(i);
            Wifi _wifi = new Wifi();
            _wifi.setSsid(scan.SSID);/*from   w  w  w.j  av a2s . c  o  m*/
            _wifi.setMacAddress(scan.BSSID);
            _wifi.setSecurity(scan.capabilities);
            _wifi.setSignalStrength(String.valueOf(scan.level));
            _wifi.setChannel(String.valueOf(getChannelFromFrequency(scan.frequency)));
            listWifi.add(_wifi);

        }
    }
}

From source file:com.example.multi_ndef.Frag_Write.java

private void initListener() {

    mWriteTagButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            initialize();/*  w  w  w  . j a  va  2  s . c om*/
            // TODO Auto-generated method stub
            network_name = ma.getWifiNetwork();
            password = ma.getWifiPassword();
            WifiManager wifi;

            String t;
            wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            List<ScanResult> results;
            results = wifi.getScanResults();
            String bssid = null;
            for (ScanResult result : results) {

                if ((network_name).equals(result.SSID)) {
                    bssid = result.BSSID;
                    break;
                }

            }

            String delimiter = ":";
            /*
             * given string will be split by the argument delimiter
             * provided.
             */
            mac_add = bssid.split(delimiter);
            /* print substrings */

            net_length = network_name.length();

            pass_length = password.length();

            Toast toast = Toast.makeText(getApplicationContext(), "Keep tag near the phone",
                    Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER | Gravity.CENTER, 0, 0);
            toast.show();

            getSMS();
            getMail();
            getLocation();
            getTelephone();

            enableWriteMode();

        }

    });

}

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  v a2  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:org.sipdroid.sipua.ui.Receiver.java

@Override
public void onReceive(Context context, Intent intent) {
    String intentAction = intent.getAction();
    if (!Sipdroid.on(context))
        return;//from  w w  w  .j  a v a  2 s .c  om
    if (!Sipdroid.release)
        Log.i("SipUA:", intentAction);
    if (mContext == null)
        mContext = context;
    if (intentAction.equals(Intent.ACTION_BOOT_COMPLETED)) {
        on_vpn(false);
        engine(context).register();
    } else if (intentAction.equals(ConnectivityManager.CONNECTIVITY_ACTION)
            || intentAction.equals(ACTION_EXTERNAL_APPLICATIONS_AVAILABLE)
            || intentAction.equals(ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)
            || intentAction.equals(Intent.ACTION_PACKAGE_REPLACED)) {
        engine(context).register();
    } else if (intentAction.equals(ACTION_VPN_CONNECTIVITY) && intent.hasExtra("connection_state")) {
        String state = intent.getSerializableExtra("connection_state").toString();
        if (state != null && on_vpn() != state.equals("CONNECTED")) {
            on_vpn(state.equals("CONNECTED"));
            for (SipProvider sip_provider : engine(context).sip_providers)
                if (sip_provider != null)
                    sip_provider.haltConnections();
            engine(context).register();
        }
    } else if (intentAction.equals(ACTION_DATA_STATE_CHANGED)) {
        engine(context).registerMore();
    } else if (intentAction.equals(ACTION_PHONE_STATE_CHANGED)
            && !intent.getBooleanExtra(context.getString(R.string.app_name), false)) {
        stopRingtone();
        pstn_state = intent.getStringExtra("state");
        pstn_time = SystemClock.elapsedRealtime();
        if (pstn_state.equals("IDLE") && call_state != UserAgent.UA_STATE_IDLE)
            broadcastCallStateChanged(null, null);
        if (!pstn_state.equals("IDLE") && call_state == UserAgent.UA_STATE_INCALL)
            mHandler.sendEmptyMessageDelayed(MSG_HOLD, 5000);
        else if (!pstn_state.equals("IDLE") && (call_state == UserAgent.UA_STATE_INCOMING_CALL
                || call_state == UserAgent.UA_STATE_OUTGOING_CALL))
            mHandler.sendEmptyMessageDelayed(MSG_HANGUP, 5000);
        else if (pstn_state.equals("IDLE")) {
            mHandler.removeMessages(MSG_HOLD);
            mHandler.removeMessages(MSG_HANGUP);
            if (call_state == UserAgent.UA_STATE_HOLD)
                mHandler.sendEmptyMessageDelayed(MSG_HOLD, 1000);
        }
    } else if (intentAction.equals(ACTION_DOCK_EVENT)) {
        docked = intent.getIntExtra(EXTRA_DOCK_STATE, -1) & 7;
        if (call_state == UserAgent.UA_STATE_INCALL)
            engine(mContext).speaker(speakermode());
    } else if (intentAction.equals(ACTION_SCO_AUDIO_STATE_CHANGED)) {
        bluetooth = intent.getIntExtra(EXTRA_SCO_AUDIO_STATE, -1);
        progress();
        RtpStreamSender.changed = true;
    } else if (intentAction.equals(Intent.ACTION_HEADSET_PLUG)) {
        headset = intent.getIntExtra("state", -1);
        if (call_state == UserAgent.UA_STATE_INCALL)
            engine(mContext).speaker(speakermode());
    } else if (intentAction.equals(Intent.ACTION_SCREEN_ON)) {
        if (!PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(
                org.sipdroid.sipua.ui.Settings.PREF_OWNWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_OWNWIFI))
            alarm(0, OwnWifi.class);
    } else if (intentAction.equals(Intent.ACTION_USER_PRESENT)) {
        mHandler.sendEmptyMessageDelayed(MSG_ENABLE, 3000);
    } else if (intentAction.equals(Intent.ACTION_SCREEN_OFF)) {
        if (PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(
                org.sipdroid.sipua.ui.Settings.PREF_OWNWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_OWNWIFI)) {
            WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wi = wm.getConnectionInfo();
            if (wm.getWifiState() != WifiManager.WIFI_STATE_ENABLED || wi == null
                    || wi.getSupplicantState() != SupplicantState.COMPLETED || wi.getIpAddress() == 0)
                alarm(2 * 60, OwnWifi.class);
            else
                alarm(15 * 60, OwnWifi.class);
        }
        if (SipdroidEngine.pwl != null)
            for (PowerManager.WakeLock pwl : SipdroidEngine.pwl)
                if (pwl != null && pwl.isHeld()) {
                    pwl.release();
                    pwl.acquire();
                }
    } else if (intentAction.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
        if (PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(
                org.sipdroid.sipua.ui.Settings.PREF_SELECTWIFI,
                org.sipdroid.sipua.ui.Settings.DEFAULT_SELECTWIFI))
            mHandler.sendEmptyMessageDelayed(MSG_SCAN, 3000);
    } else if (intentAction.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
        if (SystemClock.uptimeMillis() > lastscan + 45000
                && PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(
                        org.sipdroid.sipua.ui.Settings.PREF_SELECTWIFI,
                        org.sipdroid.sipua.ui.Settings.DEFAULT_SELECTWIFI)) {
            WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wi = wm.getConnectionInfo();
            String activeSSID = null;
            if (wi != null)
                activeSSID = wi.getSSID();
            if (activeSSID != null && (activeSSID.length() == 0 || activeSSID.equals("0x")))
                activeSSID = null;
            List<ScanResult> mScanResults = wm.getScanResults();
            List<WifiConfiguration> configurations = wm.getConfiguredNetworks();
            if (configurations != null) {
                WifiConfiguration bestconfig = null, maxconfig = null, activeconfig = null;
                for (final WifiConfiguration config : configurations) {
                    if (maxconfig == null || config.priority > maxconfig.priority) {
                        maxconfig = config;
                    }
                    if (config.SSID != null
                            && (config.SSID.equals("\"" + activeSSID + "\"") || config.SSID.equals(activeSSID)))
                        activeconfig = config;
                }
                ScanResult bestscan = null, activescan = null;
                if (mScanResults != null)
                    for (final ScanResult scan : mScanResults) {
                        for (final WifiConfiguration config : configurations) {
                            if (config.SSID != null && config.SSID.equals("\"" + scan.SSID + "\"")) {
                                if (bestscan == null || scan.level > bestscan.level) {
                                    bestscan = scan;
                                    bestconfig = config;
                                }
                                if (config == activeconfig)
                                    activescan = scan;
                            }
                        }
                    }
                if (activescan != null)
                    System.out.println("debug wifi asu(active)" + asu(activescan));
                if (bestconfig != null && (activeconfig == null || bestconfig.priority != activeconfig.priority)
                        && asu(bestscan) > asu(activescan) * 1.5 &&
                        /* (activeSSID == null || activescan != null) && */ asu(bestscan) > 22) {
                    if (!Sipdroid.release)
                        Log.i("SipUA:", "changing to " + bestconfig.SSID);
                    if (activeSSID == null || !activeSSID.equals(bestscan.SSID))
                        wm.disconnect();
                    bestconfig.priority = maxconfig.priority + 1;
                    wm.updateNetwork(bestconfig);
                    wm.enableNetwork(bestconfig.networkId, true);
                    wm.saveConfiguration();
                    if (activeSSID == null || !activeSSID.equals(bestscan.SSID))
                        wm.reconnect();
                    lastscan = SystemClock.uptimeMillis();
                } else if (activescan != null && asu(activescan) < 15) {
                    wm.disconnect();
                    wm.disableNetwork(activeconfig.networkId);
                    wm.saveConfiguration();
                }
            }
        }
    }
}