Example usage for android.net.wifi WifiManager isWifiEnabled

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

Introduction

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

Prototype

public boolean isWifiEnabled() 

Source Link

Document

Return whether Wi-Fi is enabled or disabled.

Usage

From source file:com.prey.PreyPhone.java

private void updateWifi() {
    wifi = new Wifi();
    try {/*from  w w  w. j  a  v a 2  s  . c om*/
        WifiManager wifiMgr = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();

        wifi.setWifiEnabled(wifiMgr.isWifiEnabled());

        int ipAddress = wifiInfo.getIpAddress();
        wifi.setIpAddress(formatterIp(ipAddress));
        wifi.setMacAddress(wifiInfo.getMacAddress());
        DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();
        wifi.setNetmask(formatterIp(dhcpInfo.netmask));
        wifi.setGatewayIp(formatterIp(dhcpInfo.serverAddress));
        if (ipAddress != 0) {
            wifi.setInterfaceType("Wireless");
        } else {
            if (PreyConnectivityManager.getInstance(ctx).isMobileConnected()) {
                wifi.setInterfaceType("Mobile");
            } else {
                wifi.setInterfaceType("");
            }
        }
        wifi.setName("eth0");
        String ssid = wifiInfo.getSSID();
        try {
            ssid = ssid.replaceAll("\"", "");
        } catch (Exception e) {

        }
        wifi.setSsid(ssid);

        for (int i = 0; listWifi != null && i < listWifi.size(); i++) {
            Wifi _wifi = listWifi.get(i);
            ssid = _wifi.getSsid();
            try {
                ssid = ssid.replaceAll("\"", "");
            } catch (Exception e) {

            }
            if (ssid.equals(wifi.getSsid())) {
                wifi.setSecurity(_wifi.getSecurity());
                wifi.setSignalStrength(_wifi.getSignalStrength());
                wifi.setChannel(_wifi.getChannel());
                break;
            }
        }
    } catch (Exception e) {
    }
}

From source file:uk.bowdlerize.MainActivity.java

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

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

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

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

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

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

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

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

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

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

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

From source file:de.j4velin.wifiAutoOff.Preferences.java

@SuppressWarnings("deprecation")
@Override/*  w w w .ja v  a 2  s . com*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    if (BuildConfig.DEBUG && PermissionChecker.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED) {
        requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
    }

    status = (StatusPreference) findPreference("status");
    status.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(final Preference preference) {
            WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            boolean connected = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
            if (wm.isWifiEnabled() && !connected) {
                try {
                    startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK)
                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (Exception e) {
                    Toast.makeText(Preferences.this, R.string.settings_not_found_, Toast.LENGTH_SHORT).show();
                }
            } else if (!wm.isWifiEnabled()) {
                wm.setWifiEnabled(true);
            } else {
                try {
                    startActivity(
                            new Intent(Settings.ACTION_WIFI_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (Exception e) {
                    Toast.makeText(Preferences.this, R.string.settings_not_found_, Toast.LENGTH_SHORT).show();
                }
            }
            return true;
        }
    });

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    final CheckBoxPreference screen_off = (CheckBoxPreference) findPreference("off_screen_off");
    screen_off.setSummary(
            getString(R.string.for_at_least, prefs.getInt("screen_off_timeout", Receiver.TIMEOUT_SCREEN_OFF)));

    if (!keepWiFiOn(this)) {
        screen_off.setChecked(false);
    }

    screen_off.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                if (!keepWiFiOn(Preferences.this)) {
                    new AlertDialog.Builder(Preferences.this).setMessage(R.string.sleep_policy)
                            .setPositiveButton(R.string.adv_wifi_settings, new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    try {
                                        startActivity(new Intent(Settings.ACTION_WIFI_IP_SETTINGS)
                                                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                                    } catch (Exception e) {
                                        Toast.makeText(Preferences.this, R.string.settings_not_found_,
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }).setNegativeButton(android.R.string.cancel, new OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();
                    return false;
                }
                if (android.os.Build.VERSION.SDK_INT >= 11) {
                    APILevel11Wrapper.showNumberPicker(Preferences.this, prefs, screen_off,
                            R.string.for_at_least, 1, 60, getString(R.string.minutes_before_turning_off_wifi_),
                            "screen_off_timeout", Receiver.TIMEOUT_SCREEN_OFF, false);
                } else {
                    showPre11NumberPicker(Preferences.this, prefs, screen_off, R.string.for_at_least, 1, 60,
                            getString(R.string.minutes_before_turning_off_wifi_), "screen_off_timeout",
                            Receiver.TIMEOUT_SCREEN_OFF, false);
                }
            }
            return true;
        }
    });

    findPreference("off_no_network").setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                if (android.os.Build.VERSION.SDK_INT >= 11) {
                    APILevel11Wrapper.showNumberPicker(Preferences.this, prefs, preference,
                            R.string.for_at_least, 1, 60, getString(R.string.minutes_before_turning_off_wifi_),
                            "no_network_timeout", Receiver.TIMEOUT_NO_NETWORK, false);
                } else {
                    showPre11NumberPicker(Preferences.this, prefs, preference, R.string.for_at_least, 1, 60,
                            getString(R.string.minutes_before_turning_off_wifi_), "no_network_timeout",
                            Receiver.TIMEOUT_NO_NETWORK, false);
                }
            }
            return true;
        }
    });

    final CheckBoxPreference on_at = (CheckBoxPreference) findPreference("on_at");
    on_at.setTitle(getString(R.string.at_summary, prefs.getString("on_at_time", Receiver.ON_AT_TIME)));
    on_at.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                String[] time = prefs.getString("on_at_time", Receiver.ON_AT_TIME).split(":");
                final TimePickerDialog dialog = new TimePickerDialog(Preferences.this, new OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        prefs.edit().putString("on_at_time",
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)).commit();
                        on_at.setTitle(getString(R.string.at_summary,
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)));
                    }
                }, Integer.parseInt(time[0]), Integer.parseInt(time[1]), true);
                dialog.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        on_at.setChecked(false);
                    }
                });
                dialog.setTitle(getString(R.string.turn_wifi_on_at_));
                dialog.show();
            }
            return true;
        }
    });

    final CheckBoxPreference off_at = (CheckBoxPreference) findPreference("off_at");
    off_at.setTitle(getString(R.string.at_summary, prefs.getString("off_at_time", Receiver.OFF_AT_TIME)));
    off_at.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                String[] time = prefs.getString("off_at_time", Receiver.OFF_AT_TIME).split(":");
                final TimePickerDialog dialog = new TimePickerDialog(Preferences.this, new OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        prefs.edit().putString("off_at_time",
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)).commit();
                        off_at.setTitle(getString(R.string.at_summary,
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)));
                    }
                }, Integer.parseInt(time[0]), Integer.parseInt(time[1]), true);
                dialog.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        off_at.setChecked(false);
                    }
                });
                dialog.setTitle(getString(R.string.turn_wifi_off_at_));
                dialog.show();
            }
            return true;
        }
    });

    final Preference on_every = findPreference("on_every");
    final String[] time_names = getResources().getStringArray(R.array.time_names);
    // default 2 hours
    on_every.setTitle(getString(R.string.every_summary, prefs.getString("on_every_str", time_names[4])));
    on_every.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                AlertDialog.Builder builder = new AlertDialog.Builder(Preferences.this);
                builder.setTitle(R.string.turn_wifi_on_every).setItems(time_names,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                prefs.edit().putInt("on_every_time_min", time_values[which])
                                        .putString("on_every_str", time_names[which]).commit();
                                on_every.setTitle(getString(R.string.every_summary, time_names[which]));
                            }
                        });
                builder.create().show();
            }
            return true;
        }
    });

    Preference locations = findPreference("locations");
    if (BuildConfig.FLAVOR.equals("play")) {
        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_NETWORK)) {
            locations.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(final Preference preference) {
                    startActivity(new Intent(Preferences.this, Locations.class));
                    return true;
                }
            });
        } else {
            locations.setEnabled(false);
        }
    } else {
        locations.setSummary("Not available in F-Droid version");
        locations.setEnabled(false);
    }

    final Preference power = findPreference("power_connected");
    power.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((boolean) newValue) {
                Intent battery = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
                if (battery != null && battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) > 0) {
                    // already connected to external power
                    prefs.edit().putBoolean("ignore_screen_off", true).commit();
                }
            } else {
                prefs.edit().putBoolean("ignore_screen_off", false).commit();
            }
            return true;
        }
    });
}

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

private void clean_networks() {
    StringBuilder sb = new StringBuilder();
    final WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);
    if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) {
        try {//  www  . j  a v  a  2s.c  om
            List<WifiConfiguration> listWifiCfg = wifiMgr.getConfiguredNetworks();
            for (WifiConfiguration wifiCfg : listWifiCfg) {

                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) {

                    // Remove network connections with no Password.
                    if (wifiMgr.removeNetwork(wifiCfg.networkId)) {
                        sb.append(wifiCfg.SSID);
                        sb.append("\n");
                    }
                }
            }
        } catch (Exception ex) {

        }
    }

    if (sb.length() != 0) {
        Toast.makeText(this.getContext(), "Removed Networks: " + sb.toString(), Toast.LENGTH_LONG).show();
    }
}

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

@ProtocoderScript
@APIMethod(description = "Check if the Wifi adapter is enabled", example = "")
@APIParam(params = {})/*from   www  .  j  a  v  a  2s. c o  m*/
public boolean isWifiEnabled() {
    WifiManager wifiManager = (WifiManager) a.get().getSystemService(Context.WIFI_SERVICE);
    return wifiManager.isWifiEnabled();
}

From source file:uk.org.ngo.squeezer.NowPlayingFragment.java

public void startVisibleConnection() {
    Log.v(TAG, "startVisibleConnection");
    if (mService == null) {
        return;//from   w  ww .  j ava2 s. c om
    }

    Preferences preferences = new Preferences(mActivity);

    // If we are configured to automatically connect on Wi-Fi availability
    // we will also give the user the opportunity to enable Wi-Fi
    if (preferences.isAutoConnect()) {
        WifiManager wifiManager = (WifiManager) mActivity.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            FragmentManager fragmentManager = getFragmentManager();
            if (fragmentManager != null) {
                EnableWifiDialog.show(getFragmentManager());
            } else {
                Log.i(getTag(), "fragment manager is null so we can't show EnableWifiDialog");
            }
            return;
            // When a Wi-Fi connection is made this method will be called again by the
            // broadcastReceiver
        }
    }

    Preferences.ServerAddress serverAddress = preferences.getServerAddress();
    String ipPort = serverAddress.address;
    if (ipPort == null) {
        // Set up a server connection, if it is not present
        DisconnectedActivity.show(mActivity);
        return;
    }

    if (isConnectInProgress()) {
        Log.v(TAG, "Connection is already in progress, connecting aborted");
        return;
    }
    Log.v(TAG, "startConnect, ipPort: " + ipPort);
    mService.startConnect(ipPort, preferences.getUserName(serverAddress, "test"),
            preferences.getPassword(serverAddress, "test1"));
}

From source file:com.aimfire.main.MainActivity.java

/**
 * Override Activity lifecycle method.//from  www.j  a  va 2  s  .  co m
 */
@Override
protected void onResume() {
    /*
     * we disable the wifi on/off feature as it is quite confusing. we show only a
     * toast to warn user.
     */
    WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    if (!manager.isWifiEnabled()) {
        Toast.makeText(this, R.string.error_wifi_off, Toast.LENGTH_LONG).show();
    }

    /*
     * register for intents sent by the cloud backend service
     */
    LocalBroadcastManager.getInstance(this).registerReceiver(mAimfireServiceMsgReceiver,
            new IntentFilter(MainConsts.AIMFIRE_SERVICE_MESSAGE));

    /*
     * navigate the selected tab
     */
    getSupportActionBar().setSelectedNavigationItem(mTabPosition);

    super.onResume();
}

From source file:com.intel.xdk.device.Device.java

private String getConnection() {
    WifiManager wifiMgr = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
    if (wifiMgr.isWifiEnabled() == true) {
        return "wifi";
    }//ww w  .  j av a  2  s  . c o m

    TelephonyManager telMgr = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
    int data = telMgr.getDataState();
    if (data == TelephonyManager.DATA_DISCONNECTED || data == TelephonyManager.DATA_SUSPENDED)
        return "none";
    else
        return "cell";
}

From source file:com.example.aaron.test.MyGLSurfaceView.java

public WifiInfo getWifi(Context context) {
    WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    if (manager.isWifiEnabled()) {
        WifiInfo wifiInfo = manager.getConnectionInfo();
        if (wifiInfo != null) {
            return wifiInfo;
        }//from w ww.ja v  a2  s .com
    }
    return null;
}