Example usage for android.net.wifi WifiManager disconnect

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

Introduction

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

Prototype

public boolean disconnect() 

Source Link

Document

Disassociate from the currently active access point.

Usage

From source file:Main.java

public static int disconnectWifi(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (ni != null && ni.isConnectedOrConnecting()) {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        int id = wm.getConnectionInfo().getNetworkId();
        return wm.disconnect() ? id : -1;
    }//from  www. j  ava  2s  .c o m

    return -1;
}

From source file:Main.java

/**
 * Requires {@link android.Manifest.permission#ACCESS_WIFI_STATE}
 * and {@link android.Manifest.permission#CHANGE_WIFI_STATE} permissions.
 *
 * @param context// w  ww.ja v  a2  s. c o m
 * @return
 */
@SuppressLint("MissingPermission")
public static int disconnectWifi(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (ni != null && ni.isConnectedOrConnecting()) {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        int id = wm.getConnectionInfo().getNetworkId();
        return wm.disconnect() ? id : -1;
    }

    return -1;
}

From source file:org.openremote.android.test.console.net.ORNetworkCheckTest.java

private void enableWifi(boolean enable) {

    WifiManager wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);

    if (enable && wifi.isWifiEnabled())
        return;//  w w w . ja  v  a  2  s.co m

    if (!enable && !wifi.isWifiEnabled())
        return;

    if (enable && !wifi.isWifiEnabled()) {
        if (!wifi.setWifiEnabled(true))
            fail("Cannot enable WiFi");
    } else {
        wifi.disconnect();
        wifi.setWifiEnabled(false);
    }

    // wait for it...

    for (int iterations = 0; iterations < 10; iterations++) {
        SystemClock.sleep(500);

        if (enable && wifi.isWifiEnabled())
            break;
        if (!enable && !wifi.isWifiEnabled())
            break;
    }
}

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Connect to a given Wifi network with a given 'wpa', 'wep', 'open' type and a password", example = "")
@APIParam(params = { "ssidName", "type", "password" })
public void connectWifi(String networkSSID, String type, String networkPass) {

    WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String
    // should contain ssid in quotes

    if (type.equals("wep")) {
        // wep/*from   w  w w  .  ja  v a 2 s .  c  o  m*/
        conf.wepKeys[0] = "\"" + networkPass + "\"";
        conf.wepTxKeyIndex = 0;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
    } else if (type.equals("wpa")) {
        // wpa
        conf.preSharedKey = "\"" + networkPass + "\"";
    } else if (type.equals("open")) {
        // open
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    }

    WifiManager wifiManager = (WifiManager) a.get().getSystemService(Context.WIFI_SERVICE);
    wifiManager.addNetwork(conf);

    List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
    for (WifiConfiguration i : list) {
        if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
            wifiManager.disconnect();
            wifiManager.enableNetwork(i.networkId, true);
            wifiManager.reconnect();

            break;
        }
    }

}

From source file:com.moez.QKSMS.mmssms.Transaction.java

/**
 * @deprecated/*from w ww  .j  a va  2s .  c  om*/
 */
private void revokeWifi(boolean saveState) {
    WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

    if (saveState) {
        settings.currentWifi = wifi.getConnectionInfo();
        settings.currentWifiState = wifi.isWifiEnabled();
        wifi.disconnect();
        settings.discon = new DisconnectWifi();
        context.registerReceiver(settings.discon,
                new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));
        settings.currentDataState = Utils.isMobileDataEnabled(context);
        Utils.setMobileDataEnabled(context, true);
    } else {
        wifi.disconnect();
        wifi.disconnect();
        settings.discon = new DisconnectWifi();
        context.registerReceiver(settings.discon,
                new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));
        Utils.setMobileDataEnabled(context, true);
    }
}

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  av  a 2 s. com*/
    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();
                }
            }
        }
    }
}