diff options
Diffstat (limited to 'src/com/android/settings/wifi')
-rw-r--r-- | src/com/android/settings/wifi/AccessPointDialog.java | 600 | ||||
-rw-r--r-- | src/com/android/settings/wifi/AccessPointPreference.java | 108 | ||||
-rw-r--r-- | src/com/android/settings/wifi/AccessPointState.java | 879 | ||||
-rw-r--r-- | src/com/android/settings/wifi/AdvancedSettings.java | 272 | ||||
-rw-r--r-- | src/com/android/settings/wifi/WifiEnabler.java | 188 | ||||
-rw-r--r-- | src/com/android/settings/wifi/WifiLayer.java | 1302 | ||||
-rw-r--r-- | src/com/android/settings/wifi/WifiSettings.java | 438 | ||||
-rw-r--r-- | src/com/android/settings/wifi/WifiStatus.java | 152 |
8 files changed, 0 insertions, 3939 deletions
diff --git a/src/com/android/settings/wifi/AccessPointDialog.java b/src/com/android/settings/wifi/AccessPointDialog.java deleted file mode 100644 index 917ed96..0000000 --- a/src/com/android/settings/wifi/AccessPointDialog.java +++ /dev/null @@ -1,600 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.settings.wifi; - -import com.android.settings.R; - -import android.app.AlertDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.net.wifi.WifiInfo; -import android.net.wifi.WifiManager; -import android.os.Bundle; -import android.text.TextUtils; -import android.text.format.Formatter; -import android.text.method.PasswordTransformationMethod; -import android.text.method.TransformationMethod; -import android.util.Log; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.CheckBox; -import android.widget.EditText; -import android.widget.Spinner; -import android.widget.TableLayout; -import android.widget.TextView; - -public class AccessPointDialog extends AlertDialog implements DialogInterface.OnClickListener, - AdapterView.OnItemSelectedListener, View.OnClickListener { - - private static final String TAG = "AccessPointDialog"; - private static final String INSTANCE_KEY_ACCESS_POINT_STATE = - "com.android.settings.wifi.AccessPointDialog:accessPointState"; - private static final String INSTANCE_KEY_MODE = - "com.android.settings.wifi.AccessPointDialog:mode"; - private static final String INSTANCE_KEY_CUSTOM_TITLE = - "com.android.settings.wifi.AccessPointDialog:customTitle"; - private static final String INSTANCE_KEY_AUTO_SECURITY_ALLOWED = - "com.android.settings.wifi.AccessPointDialog:autoSecurityAllowed"; - - private static final int POSITIVE_BUTTON = BUTTON1; - private static final int NEGATIVE_BUTTON = BUTTON2; - private static final int NEUTRAL_BUTTON = BUTTON3; - - /** The dialog should show info connectivity functionality */ - public static final int MODE_INFO = 0; - /** The dialog should configure the detailed AP properties */ - public static final int MODE_CONFIGURE = 1; - /** The dialog should have the password field and connect/cancel */ - public static final int MODE_RETRY_PASSWORD = 2; - - // These should be matched with the XML. Both arrays in XML depend on this - // ordering! - private static final int SECURITY_AUTO = 0; - private static final int SECURITY_NONE = 1; - private static final int SECURITY_WEP = 2; - private static final int SECURITY_WPA_PERSONAL = 3; - private static final int SECURITY_WPA2_PERSONAL = 4; - - private static final int[] WEP_TYPE_VALUES = { - AccessPointState.WEP_PASSWORD_AUTO, AccessPointState.WEP_PASSWORD_ASCII, - AccessPointState.WEP_PASSWORD_HEX - }; - - // Button positions, default to impossible values - private int mConnectButtonPos = Integer.MAX_VALUE; - private int mForgetButtonPos = Integer.MAX_VALUE; - private int mSaveButtonPos = Integer.MAX_VALUE; - - // Client configurable items. Generally, these should be saved in instance state - private int mMode = MODE_INFO; - private boolean mAutoSecurityAllowed = true; - private CharSequence mCustomTitle; - // This does not need to be saved in instance state. - private WifiLayer mWifiLayer; - private AccessPointState mState; - - // General views - private View mView; - private TextView mPasswordText; - private EditText mPasswordEdit; - private CheckBox mShowPasswordCheckBox; - - // Info-specific views - private ViewGroup mTable; - - // Configure-specific views - private EditText mSsidEdit; - private Spinner mSecuritySpinner; - private Spinner mWepTypeSpinner; - - public AccessPointDialog(Context context, WifiLayer wifiLayer) { - super(context); - - mWifiLayer = wifiLayer; - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - onLayout(); - onFill(); - - super.onCreate(savedInstanceState); - } - - @Override - public void onRestoreInstanceState(Bundle savedInstanceState) { - // Set to a class loader that can find AccessPointState - savedInstanceState.setClassLoader(getClass().getClassLoader()); - - mState = savedInstanceState.getParcelable(INSTANCE_KEY_ACCESS_POINT_STATE); - mState.setContext(getContext()); - - mMode = savedInstanceState.getInt(INSTANCE_KEY_MODE, mMode); - mAutoSecurityAllowed = savedInstanceState.getBoolean(INSTANCE_KEY_AUTO_SECURITY_ALLOWED, - mAutoSecurityAllowed); - mCustomTitle = savedInstanceState.getCharSequence(INSTANCE_KEY_CUSTOM_TITLE); - if (mCustomTitle != null) { - setTitle(mCustomTitle); - } - - // This is called last since it depends on the above values - super.onRestoreInstanceState(savedInstanceState); - - if (mShowPasswordCheckBox != null) { - // Restore the show-password-state on the edit text - setShowPassword(mShowPasswordCheckBox.isChecked()); - } - } - - @Override - public Bundle onSaveInstanceState() { - Bundle bundle = super.onSaveInstanceState(); - bundle.putParcelable(INSTANCE_KEY_ACCESS_POINT_STATE, mState); - bundle.putInt(INSTANCE_KEY_MODE, mMode); - bundle.putBoolean(INSTANCE_KEY_AUTO_SECURITY_ALLOWED, mAutoSecurityAllowed); - bundle.putCharSequence(INSTANCE_KEY_CUSTOM_TITLE, mCustomTitle); - return bundle; - } - - /** - * Sets state to show in this dialog. - * - * @param state The state. - */ - public void setState(AccessPointState state) { - mState = state; - } - - /** - * Sets the dialog mode. - * @param mode One of {@link #MODE_CONFIGURE} or {@link #MODE_INFO} - */ - public void setMode(int mode) { - mMode = mode; - } - - public void setAutoSecurityAllowed(boolean autoSecurityAllowed) { - mAutoSecurityAllowed = autoSecurityAllowed; - } - - @Override - public void setTitle(CharSequence title) { - super.setTitle(title); - mCustomTitle = title; - } - - @Override - public void setTitle(int titleId) { - setTitle(getContext().getString(titleId)); - } - - /** Called after flags are set, the dialog's layout/etc should be set up here */ - private void onLayout() { - final Context context = getContext(); - final String ssid = mState.getHumanReadableSsid(); - - int positiveButtonResId = 0; - int negativeButtonResId = R.string.cancel; - int neutralButtonResId = 0; - - if (mCustomTitle == null) { - // Generic title is the SSID - // We don't want to trigger this as a custom title, so call super's - super.setTitle(ssid); - } - setInverseBackgroundForced(true); - - boolean defaultPasswordVisibility = true; - - if (mMode == MODE_CONFIGURE) { - setLayout(R.layout.wifi_ap_configure); - - positiveButtonResId = R.string.wifi_save_config; - mSaveButtonPos = POSITIVE_BUTTON; - - } else if (mMode == MODE_INFO) { - setLayout(R.layout.wifi_ap_info); - - if (mState.isConnectable()) { - if (mCustomTitle == null) { - // We don't want to trigger this as a custom title, so call super's - super.setTitle(context.getString(R.string.connect_to_blank, ssid)); - } - positiveButtonResId = R.string.connect; - mConnectButtonPos = POSITIVE_BUTTON; - } - - if (mState.isForgetable()) { - if (positiveButtonResId == 0) { - positiveButtonResId = R.string.forget_network; - mForgetButtonPos = POSITIVE_BUTTON; - } else { - neutralButtonResId = R.string.forget_network; - mForgetButtonPos = NEUTRAL_BUTTON; - } - } - } else if (mMode == MODE_RETRY_PASSWORD) { - setLayout(R.layout.wifi_ap_retry_password); - - positiveButtonResId = R.string.connect; - mConnectButtonPos = POSITIVE_BUTTON; - - setGenericPasswordVisible(true); - defaultPasswordVisibility = false; - } - - if (defaultPasswordVisibility) { - if (!mState.configured && mState.seen && mState.hasSecurity()) { - setGenericPasswordVisible(true); - } else { - setGenericPasswordVisible(false); - } - } - - setButtons(positiveButtonResId, negativeButtonResId, neutralButtonResId); - } - - /** Called when we need to set our member variables to point to the views. */ - private void onReferenceViews(View view) { - mPasswordText = (TextView) view.findViewById(R.id.password_text); - mPasswordEdit = (EditText) view.findViewById(R.id.password_edit); - - mShowPasswordCheckBox = (CheckBox) view.findViewById(R.id.show_password_checkbox); - if (mShowPasswordCheckBox != null) { - mShowPasswordCheckBox.setOnClickListener(this); - } - - if (mMode == MODE_CONFIGURE) { - mSsidEdit = (EditText) view.findViewById(R.id.ssid_edit); - mSecuritySpinner = (Spinner) view.findViewById(R.id.security_spinner); - mSecuritySpinner.setOnItemSelectedListener(this); - setSecuritySpinnerAdapter(); - mWepTypeSpinner = (Spinner) view.findViewById(R.id.wep_type_spinner); - - } else if (mMode == MODE_INFO) { - mTable = (ViewGroup) view.findViewById(R.id.table); - } - - } - - private void setSecuritySpinnerAdapter() { - Context context = getContext(); - int arrayResId = mAutoSecurityAllowed ? R.array.wifi_security_entries - : R.array.wifi_security_without_auto_entries; - - ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(context, - android.R.layout.simple_spinner_item, - context.getResources().getStringArray(arrayResId)); - adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); - mSecuritySpinner.setAdapter(adapter); - } - - /** Called when the widgets are in-place waiting to be filled with data */ - private void onFill() { - - // Appears in the order added - if (mMode == MODE_INFO) { - if (mState.primary) { - addInfoRow(R.string.wifi_status, mState.getSummarizedStatus()); - addInfoRow(R.string.wifi_link_speed, mState.linkSpeed + WifiInfo.LINK_SPEED_UNITS); - } - - if (mState.seen) { - addInfoRow(R.string.signal, getSignalResId(mState.signal)); - } - - if (mState.security != null) { - addInfoRow(R.string.security, mState.getHumanReadableSecurity()); - } - - if (mState.primary && mState.ipAddress != 0) { - addInfoRow(R.string.ip_address, Formatter.formatIpAddress(mState.ipAddress)); - } - - } else if (mMode == MODE_CONFIGURE) { - String ssid = mState.getHumanReadableSsid(); - if (!TextUtils.isEmpty(ssid)) { - mSsidEdit.setText(ssid); - } - - mPasswordEdit.setHint(R.string.wifi_password_unchanged); - } - - updatePasswordCaption(mState.security); - } - - private void updatePasswordCaption(String security) { - - if (mPasswordText != null && security != null - && security.equals(AccessPointState.WEP)) { - mPasswordText.setText(R.string.please_type_hex_key); - } else { - mPasswordText.setText(R.string.please_type_passphrase); - } - } - - private void addInfoRow(int nameResId, String value) { - View rowView = getLayoutInflater().inflate(R.layout.wifi_ap_info_row, mTable, false); - ((TextView) rowView.findViewById(R.id.name)).setText(nameResId); - ((TextView) rowView.findViewById(R.id.value)).setText(value); - mTable.addView(rowView); - } - - private void addInfoRow(int nameResId, int valueResId) { - addInfoRow(nameResId, getContext().getString(valueResId)); - } - - private void setButtons(int positiveResId, int negativeResId, int neutralResId) { - final Context context = getContext(); - - if (positiveResId > 0) { - setButton(context.getString(positiveResId), this); - } - - if (negativeResId > 0) { - setButton2(context.getString(negativeResId), this); - } - - if (neutralResId > 0) { - setButton3(context.getString(neutralResId), this); - } - } - - private void setLayout(int layoutResId) { - setView(mView = getLayoutInflater().inflate(layoutResId, null)); - onReferenceViews(mView); - } - - public void onClick(DialogInterface dialog, int which) { - if (which == mForgetButtonPos) { - handleForget(); - } else if (which == mConnectButtonPos) { - handleConnect(); - } else if (which == mSaveButtonPos) { - handleSave(); - } - } - - private void handleForget() { - if (!replaceStateWithWifiLayerInstance()) return; - mWifiLayer.forgetNetwork(mState); - } - - private void handleConnect() { - if (!replaceStateWithWifiLayerInstance()) { - Log.w(TAG, "Assuming connecting to a new network."); - } - - /* - * If the network is secured and they haven't entered a password, popup - * an error. Allow empty passwords if the state already has a password - * set (since in that scenario, an empty password means keep the old - * password). - */ - String password = getEnteredPassword(); - boolean passwordIsEmpty = TextUtils.isEmpty(password); - - /* - * When 'retry password', they can not enter a blank password. In any - * other mode, we let them enter a blank password if the state already - * has a password. - */ - if (passwordIsEmpty && (!mState.hasPassword() || mMode == MODE_RETRY_PASSWORD) - && (mState.security != null) && !mState.security.equals(AccessPointState.OPEN)) { - new AlertDialog.Builder(getContext()) - .setTitle(R.string.error_title) - .setIcon(android.R.drawable.ic_dialog_alert) - .setMessage(R.string.wifi_password_incorrect_error) - .setPositiveButton(android.R.string.ok, null) - .show(); - return; - } - - if (!passwordIsEmpty) { - mState.setPassword(password); - } - - mWifiLayer.connectToNetwork(mState); - } - - private void handleSave() { - replaceStateWithWifiLayerInstance(); - - String ssid = mSsidEdit.getText().toString(); - String password = mPasswordEdit.getText().toString(); - - mState.setSsid(ssid); - - int securityType = getSecurityTypeFromSpinner(); - - if (!TextUtils.isEmpty(password)) { - switch (securityType) { - - case SECURITY_WPA_PERSONAL: { - mState.setSecurity(AccessPointState.WPA); - mState.setPassword(password); - break; - } - - case SECURITY_WPA2_PERSONAL: { - mState.setSecurity(AccessPointState.WPA2); - mState.setPassword(password); - break; - } - - case SECURITY_AUTO: { - mState.setPassword(password); - break; - } - - case SECURITY_WEP: { - mState.setSecurity(AccessPointState.WEP); - mState.setPassword(password, - WEP_TYPE_VALUES[mWepTypeSpinner.getSelectedItemPosition()]); - break; - } - - } - } else { - mState.setSecurity(AccessPointState.OPEN); - } - - if (securityType == SECURITY_NONE) { - mState.setSecurity(AccessPointState.OPEN); - } - - if (!mWifiLayer.saveNetwork(mState)) { - return; - } - - // Connect right away if they've touched it - if (!mWifiLayer.connectToNetwork(mState)) { - return; - } - - } - - /** - * Replaces our {@link #mState} with the equal WifiLayer instance. This is useful after - * we unparceled the state previously and before we are calling methods on {@link #mWifiLayer}. - * - * @return Whether WifiLayer was able to find an equal state in its set. - */ - private boolean replaceStateWithWifiLayerInstance() { - AccessPointState state = mWifiLayer.getWifiLayerApInstance(mState); - if (state == null) { - return false; - } - - mState = state; - return true; - } - - private int getSecurityTypeFromSpinner() { - int position = mSecuritySpinner.getSelectedItemPosition(); - // If there is no AUTO choice, the position needs 1 added to get - // to the proper spinner position -> security constants mapping - return mAutoSecurityAllowed ? position : position + 1; - } - - private String getEnteredPassword() { - return mPasswordEdit != null ? mPasswordEdit.getText().toString() : null; - } - - /** - * Call the one you want to hide first. - */ - private void setWepVisible(boolean visible) { - setGenericPasswordVisible(visible); - int visibility = visible ? View.VISIBLE : View.GONE; - mWepTypeSpinner.setVisibility(visibility); - } - - /** - * @see #setWepVisible(boolean) - */ - private void setGenericPasswordVisible(boolean visible) { - int visibility = visible ? View.VISIBLE : View.GONE; - mPasswordText.setVisibility(visibility); - mPasswordEdit.setVisibility(visibility); - mShowPasswordCheckBox.setVisibility(visibility); - } - - public void onItemSelected(AdapterView parent, View view, int position, long id) { - if (parent == mSecuritySpinner) { - handleSecurityChange(getSecurityTypeFromSpinner()); - } - } - - public void onNothingSelected(AdapterView parent) { - } - - private void handleSecurityChange(int security) { - - switch (security) { - - case SECURITY_NONE: { - setWepVisible(false); - setGenericPasswordVisible(false); - break; - } - - case SECURITY_WEP: { - setGenericPasswordVisible(false); - setWepVisible(true); - updatePasswordCaption(AccessPointState.WEP); - break; - } - - case SECURITY_AUTO: { - setWepVisible(false); - setGenericPasswordVisible(mState.hasSecurity()); - // Shows the generic 'wireless password' - updatePasswordCaption(AccessPointState.WPA); - break; - } - - case SECURITY_WPA_PERSONAL: - case SECURITY_WPA2_PERSONAL: { - setWepVisible(false); - setGenericPasswordVisible(true); - // Both WPA and WPA2 show the same caption, so either is ok - updatePasswordCaption(AccessPointState.WPA); - break; - } - } - } - - private static int getSignalResId(int signal) { - switch (WifiManager.calculateSignalLevel(signal, 4)) { - case 0: { - return R.string.wifi_signal_0; - } - case 1: { - return R.string.wifi_signal_1; - } - case 2: { - return R.string.wifi_signal_2; - } - case 3: { - return R.string.wifi_signal_3; - } - } - - return 0; - } - - - public void onClick(View v) { - if (v == mShowPasswordCheckBox) { - setShowPassword(mShowPasswordCheckBox.isChecked()); - } - } - - private void setShowPassword(boolean showPassword) { - if (mPasswordEdit != null) { - // Toggle password - mPasswordEdit.setTransformationMethod( - showPassword ? - null : - PasswordTransformationMethod.getInstance()); - } - } - -} diff --git a/src/com/android/settings/wifi/AccessPointPreference.java b/src/com/android/settings/wifi/AccessPointPreference.java deleted file mode 100644 index 10e0947..0000000 --- a/src/com/android/settings/wifi/AccessPointPreference.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.settings.wifi; - -import com.android.settings.R; - -import android.net.wifi.WifiManager; -import android.preference.Preference; -import android.view.View; -import android.widget.ImageView; - -public class AccessPointPreference extends Preference implements - AccessPointState.AccessPointStateCallback { - - // UI states - private static final int[] STATE_ENCRYPTED = { R.attr.state_encrypted }; - private static final int[] STATE_EMPTY = { }; - - // Signal strength indicator - private static final int UI_SIGNAL_LEVELS = 4; - - private WifiSettings mWifiSettings; - - private AccessPointState mState; - - public AccessPointPreference(WifiSettings wifiSettings, AccessPointState state) { - super(wifiSettings, null); - - mWifiSettings = wifiSettings; - mState = state; - - setWidgetLayoutResource(R.layout.preference_widget_wifi_signal); - - state.setCallback(this); - - refresh(); - } - - public void refresh() { - setTitle(mState.getHumanReadableSsid()); - setSummary(mState.getSummarizedStatus()); - - notifyChanged(); - } - - public void refreshAccessPointState() { - refresh(); - - // The ordering of access points could have changed due to the state change, so - // re-evaluate ordering - notifyHierarchyChanged(); - } - - @Override - protected void onBindView(View view) { - super.onBindView(view); - - ImageView signal = (ImageView) view.findViewById(R.id.signal); - if (mState.seen) { - signal.setImageResource(R.drawable.wifi_signal); - signal.setImageState(mState.hasSecurity() ? STATE_ENCRYPTED : STATE_EMPTY, true); - signal.setImageLevel(getUiSignalLevel()); - } else { - signal.setImageDrawable(null); - } - } - - private int getUiSignalLevel() { - return mState != null ? WifiManager.calculateSignalLevel(mState.signal, UI_SIGNAL_LEVELS) - : 0; - } - - /** - * Returns the {@link AccessPointState} associated with this preference. - * @return The {@link AccessPointState}. - */ - public AccessPointState getAccessPointState() { - return mState; - } - - @Override - public int compareTo(Preference another) { - if (!(another instanceof AccessPointPreference)) { - // Let normal preferences go before us. - // NOTE: we should only be compared to Preference in our - // category. - return 1; - } - - return mState.compareTo(((AccessPointPreference) another).mState); - } - -} - diff --git a/src/com/android/settings/wifi/AccessPointState.java b/src/com/android/settings/wifi/AccessPointState.java deleted file mode 100644 index c224954..0000000 --- a/src/com/android/settings/wifi/AccessPointState.java +++ /dev/null @@ -1,879 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.settings.wifi; - -import com.android.settings.R; - -import android.content.Context; -import android.net.NetworkInfo; -import android.net.wifi.ScanResult; -import android.net.wifi.WifiConfiguration; -import android.net.wifi.WifiInfo; -import android.net.wifi.WifiConfiguration.AuthAlgorithm; -import android.net.wifi.WifiConfiguration.GroupCipher; -import android.net.wifi.WifiConfiguration.KeyMgmt; -import android.net.wifi.WifiConfiguration.PairwiseCipher; -import android.net.wifi.WifiConfiguration.Protocol; -import android.os.Parcel; -import android.os.Parcelable; -import android.text.TextUtils; -import android.util.Log; - -public final class AccessPointState implements Comparable<AccessPointState>, Parcelable { - - private static final String TAG = "AccessPointState"; - - // Constants used for different security types - public static final String WPA2 = "WPA2"; - public static final String WPA = "WPA"; - public static final String WEP = "WEP"; - public static final String OPEN = "Open"; - - /** String present in capabilities if the scan result is ad-hoc */ - private static final String ADHOC_CAPABILITY = "[IBSS]"; - /** String present in capabilities if the scan result is enterprise secured */ - private static final String ENTERPRISE_CAPABILITY = "-EAP-"; - - // Localized strings for different security types - private static String LOCALIZED_WPA2; - private static String LOCALIZED_WPA; - private static String LOCALIZED_WEP; - private static String LOCALIZED_OPEN; - private static String LOCALIZED_UNKNOWN; - private static String LOCALIZED_VERBOSE_WPA2; - private static String LOCALIZED_VERBOSE_WPA; - private static String LOCALIZED_VERBOSE_WEP; - private static String LOCALIZED_VERBOSE_OPEN; - - - // Localized strings for various messages - private static String SUMMARY_NOT_IN_RANGE; - private static String SUMMARY_REMEMBERED; - private static String SUMMARY_CONNECTION_FAILED; - - public static final String BSSID_ANY = "any"; - public static final int NETWORK_ID_NOT_SET = -1; - /** This should be used with care! */ - static final int NETWORK_ID_ANY = -2; - - public static final int MATCH_NONE = 0; - public static final int MATCH_WEAK = 1; - public static final int MATCH_STRONG = 2; - public static final int MATCH_EXACT = 3; - - // Don't set these directly, use the setters. - public int networkId; - public int priority; - public boolean hiddenSsid; - public int linkSpeed; - public int ipAddress; - public String bssid; - public String ssid; - public int signal; - public boolean primary; - public boolean seen; - public boolean configured; - public NetworkInfo.DetailedState status; - public String security; - public boolean disabled; - - /** - * Use this for sorting based on signal strength. It is a heavily-damped - * time-averaged weighted signal. - */ - private float signalForSorting = Float.MIN_VALUE; - - private static final float DAMPING_FACTOR = 0.2f; - - /** - * This will be a user entered password, and NOT taken from wpa_supplicant - * (since it would give us *) - */ - private String mPassword; - private boolean mConfigHadPassword; - - public static final int WEP_PASSWORD_AUTO = 0; - public static final int WEP_PASSWORD_ASCII = 1; - public static final int WEP_PASSWORD_HEX = 2; - private int mWepPasswordType; - - private Context mContext; - - /** - * If > 0, don't refresh (changes are being batched), use - * {@link #blockRefresh()} and {@link #unblockRefresh()} only. - */ - private int mBlockRefresh; - /** - * This will be set by {@link #requestRefresh} and shouldn't be written to - * elsewhere. - */ - private boolean mNeedsRefresh; - - private AccessPointStateCallback mCallback; - - private StringBuilder mSummaryBuilder = new StringBuilder(); - - interface AccessPointStateCallback { - void refreshAccessPointState(); - } - - public AccessPointState(Context context) { - this(); - - setContext(context); - } - - private AccessPointState() { - bssid = BSSID_ANY; - ssid = ""; - networkId = NETWORK_ID_NOT_SET; - hiddenSsid = false; - } - - void setContext(Context context) { - mContext = context; - setStrings(); - } - - private void setStrings() { - final Context c = mContext; - - if (SUMMARY_NOT_IN_RANGE == null && c != null) { - SUMMARY_NOT_IN_RANGE = c.getString(R.string.summary_not_in_range); - SUMMARY_REMEMBERED = c.getString(R.string.summary_remembered); - SUMMARY_CONNECTION_FAILED = c.getString(R.string.summary_connection_failed); - - LOCALIZED_OPEN = c.getString(R.string.wifi_security_open); - LOCALIZED_WEP = c.getString(R.string.wifi_security_wep); - LOCALIZED_WPA = c.getString(R.string.wifi_security_wpa); - LOCALIZED_WPA2 = c.getString(R.string.wifi_security_wpa2); - - LOCALIZED_VERBOSE_OPEN = c.getString(R.string.wifi_security_verbose_open); - LOCALIZED_VERBOSE_WEP = c.getString(R.string.wifi_security_verbose_wep); - LOCALIZED_VERBOSE_WPA = c.getString(R.string.wifi_security_verbose_wpa); - LOCALIZED_VERBOSE_WPA2 = c.getString(R.string.wifi_security_verbose_wpa2); - - LOCALIZED_UNKNOWN = c.getString(R.string.wifi_security_unknown); - } - } - - public void setNetworkId(int networkId) { - this.networkId = networkId; - } - - public void setBssid(String bssid) { - if (bssid != null) { - // If the BSSID is a wildcard, do NOT let a specific BSSID replace it - if (!this.bssid.equals(BSSID_ANY)) { - this.bssid = bssid; - } - } - } - - private String getWpaSupplicantBssid() { - return bssid.equals(BSSID_ANY) ? null : bssid; - } - - public static String convertToQuotedString(String string) { - if (TextUtils.isEmpty(string)) { - return ""; - } - - final int lastPos = string.length() - 1; - if (lastPos < 0 || (string.charAt(0) == '"' && string.charAt(lastPos) == '"')) { - return string; - } - - return "\"" + string + "\""; - } - - public void setPrimary(boolean primary) { - if (this.primary != primary) { - this.primary = primary; - requestRefresh(); - } - } - - public void setSeen(boolean seen) { - if (this.seen != seen) { - this.seen = seen; - requestRefresh(); - } - } - - public void setDisabled(boolean disabled) { - if (this.disabled != disabled) { - this.disabled = disabled; - requestRefresh(); - } - } - - public void setSignal(int signal) { - - if (signalForSorting == Float.MIN_VALUE) { - signalForSorting = signal; - } else { - signalForSorting = (DAMPING_FACTOR * signal) + ((1-DAMPING_FACTOR) * signalForSorting); - } - - if (this.signal != signal) { - this.signal = signal; - requestRefresh(); - } - } - - public String getHumanReadableSsid() { - if (TextUtils.isEmpty(ssid)) { - return ""; - } - - final int lastPos = ssid.length() - 1; - if (ssid.charAt(0) == '"' && ssid.charAt(lastPos) == '"') { - return ssid.substring(1, lastPos); - } - - return ssid; - } - - public void setSsid(String ssid) { - if (ssid != null) { - this.ssid = convertToQuotedString(ssid); - requestRefresh(); - } - } - - public void setPriority(int priority) { - if (this.priority != priority) { - this.priority = priority; - requestRefresh(); - } - } - - public void setHiddenSsid(boolean hiddenSsid) { - if (this.hiddenSsid != hiddenSsid) { - this.hiddenSsid = hiddenSsid; - requestRefresh(); - } - } - - public void setLinkSpeed(int linkSpeed) { - if (this.linkSpeed != linkSpeed) { - this.linkSpeed = linkSpeed; - requestRefresh(); - } - } - - public void setIpAddress(int address) { - if (ipAddress != address) { - ipAddress = address; - requestRefresh(); - } - } - - public void setConfigured(boolean configured) { - if (this.configured != configured) { - this.configured = configured; - requestRefresh(); - } - } - - public void setStatus(NetworkInfo.DetailedState status) { - if (this.status != status) { - this.status = status; - requestRefresh(); - } - } - - public void setSecurity(String security) { - if (TextUtils.isEmpty(this.security) || !this.security.equals(security)) { - this.security = security; - requestRefresh(); - } - } - - public boolean hasSecurity() { - return security != null && !security.contains(OPEN); - } - - public String getHumanReadableSecurity() { - if (security.equals(OPEN)) return LOCALIZED_OPEN; - else if (security.equals(WEP)) return LOCALIZED_WEP; - else if (security.equals(WPA)) return LOCALIZED_WPA; - else if (security.equals(WPA2)) return LOCALIZED_WPA2; - - return LOCALIZED_UNKNOWN; - } - - public void updateFromScanResult(ScanResult scanResult) { - blockRefresh(); - - // We don't keep specific AP BSSIDs and instead leave that as wildcard - - setSeen(true); - setSsid(scanResult.SSID); - if (networkId == NETWORK_ID_NOT_SET) { - // Since ScanResults don't cross-reference network ID, we set it as a wildcard - setNetworkId(NETWORK_ID_ANY); - } - setSignal(scanResult.level); - setSecurity(getScanResultSecurity(scanResult)); - unblockRefresh(); - } - - /** - * @return The security of a given {@link ScanResult}. - */ - public static String getScanResultSecurity(ScanResult scanResult) { - final String cap = scanResult.capabilities; - final String[] securityModes = { WEP, WPA, WPA2 }; - for (int i = securityModes.length - 1; i >= 0; i--) { - if (cap.contains(securityModes[i])) { - return securityModes[i]; - } - } - - return OPEN; - } - - /** - * @return Whether the given ScanResult represents an adhoc network. - */ - public static boolean isAdhoc(ScanResult scanResult) { - return scanResult.capabilities.contains(ADHOC_CAPABILITY); - } - - /** - * @return Whether the given ScanResult has enterprise security. - */ - public static boolean isEnterprise(ScanResult scanResult) { - return scanResult.capabilities.contains(ENTERPRISE_CAPABILITY); - } - - public void updateFromWifiConfiguration(WifiConfiguration wifiConfig) { - if (wifiConfig != null) { - blockRefresh(); - setBssid(wifiConfig.BSSID); - setNetworkId(wifiConfig.networkId); - setPriority(wifiConfig.priority); - setHiddenSsid(wifiConfig.hiddenSSID); - setSsid(wifiConfig.SSID); - setConfigured(true); - setDisabled(wifiConfig.status == WifiConfiguration.Status.DISABLED); - parseWifiConfigurationSecurity(wifiConfig); - unblockRefresh(); - } - } - - public void setPassword(String password) { - setPassword(password, WEP_PASSWORD_AUTO); - } - - public void setPassword(String password, int wepPasswordType) { - mPassword = password; - mWepPasswordType = wepPasswordType; - } - - public boolean hasPassword() { - return !TextUtils.isEmpty(mPassword) || mConfigHadPassword; - } - - private static boolean hasPassword(WifiConfiguration wifiConfig) { - return !TextUtils.isEmpty(wifiConfig.preSharedKey) - || !TextUtils.isEmpty(wifiConfig.wepKeys[0]) - || !TextUtils.isEmpty(wifiConfig.wepKeys[1]) - || !TextUtils.isEmpty(wifiConfig.wepKeys[2]) - || !TextUtils.isEmpty(wifiConfig.wepKeys[3]); - } - - private void parseWifiConfigurationSecurity(WifiConfiguration wifiConfig) { - setSecurity(getWifiConfigurationSecurity(wifiConfig)); - mConfigHadPassword = hasPassword(wifiConfig); - } - - /** - * @return The security of a given {@link WifiConfiguration}. - */ - public static String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) { - - if (wifiConfig.allowedKeyManagement.get(KeyMgmt.NONE)) { - // If we never set group ciphers, wpa_supplicant puts all of them. - // For open, we don't set group ciphers. - // For WEP, we specifically only set WEP40 and WEP104, so CCMP - // and TKIP should not be there. - if (!wifiConfig.allowedGroupCiphers.get(GroupCipher.CCMP) - && (wifiConfig.allowedGroupCiphers.get(GroupCipher.WEP40) - || wifiConfig.allowedGroupCiphers.get(GroupCipher.WEP104))) { - return WEP; - } else { - return OPEN; - } - } else if (wifiConfig.allowedProtocols.get(Protocol.RSN)) { - return WPA2; - } else if (wifiConfig.allowedProtocols.get(Protocol.WPA)) { - return WPA; - } else { - Log.w(TAG, "Unknown security type from WifiConfiguration, falling back on open."); - return OPEN; - } - } - - public void updateFromWifiInfo(WifiInfo wifiInfo, NetworkInfo.DetailedState state) { - if (wifiInfo != null) { - blockRefresh(); - setBssid(wifiInfo.getBSSID()); - setLinkSpeed(wifiInfo.getLinkSpeed()); - setNetworkId(wifiInfo.getNetworkId()); - setIpAddress(wifiInfo.getIpAddress()); - setSsid(wifiInfo.getSSID()); - if (state != null) { - setStatus(state); - } - setHiddenSsid(wifiInfo.getHiddenSSID()); - unblockRefresh(); - } - } - - /** - * @return Whether this AP can be connected to at the moment. - */ - public boolean isConnectable() { - return !primary && seen; - } - - /** - * @return Whether this AP can be forgotten at the moment. - */ - public boolean isForgetable() { - return configured; - } - - /** - * Updates the state as if it were never configured. - * <p> - * Note: This will not pass the forget call to the Wi-Fi API. - */ - public void forget() { - blockRefresh(); - setConfigured(false); - setNetworkId(NETWORK_ID_NOT_SET); - setPrimary(false); - setStatus(null); - setDisabled(false); - unblockRefresh(); - } - - public void updateWifiConfiguration(WifiConfiguration config) { - config.BSSID = getWpaSupplicantBssid(); - config.priority = priority; - config.hiddenSSID = hiddenSsid; - config.SSID = convertToQuotedString(ssid); - - setupSecurity(config); - } - - private void setupSecurity(WifiConfiguration config) { - config.allowedAuthAlgorithms.clear(); - config.allowedGroupCiphers.clear(); - config.allowedKeyManagement.clear(); - config.allowedPairwiseCiphers.clear(); - config.allowedProtocols.clear(); - - if (TextUtils.isEmpty(security)) { - security = OPEN; - Log.w(TAG, "Empty security, assuming open"); - } - - if (security.equals(WEP)) { - - // If password is empty, it should be left untouched - if (!TextUtils.isEmpty(mPassword)) { - if (mWepPasswordType == WEP_PASSWORD_AUTO) { - if (isHexWepKey(mPassword)) { - config.wepKeys[0] = mPassword; - } else { - config.wepKeys[0] = convertToQuotedString(mPassword); - } - } else { - config.wepKeys[0] = mWepPasswordType == WEP_PASSWORD_ASCII - ? convertToQuotedString(mPassword) - : mPassword; - } - } - - config.wepTxKeyIndex = 0; - - config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN); - config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED); - - config.allowedKeyManagement.set(KeyMgmt.NONE); - - config.allowedGroupCiphers.set(GroupCipher.WEP40); - config.allowedGroupCiphers.set(GroupCipher.WEP104); - - } else if (security.equals(WPA) || security.equals(WPA2)){ - config.allowedGroupCiphers.set(GroupCipher.TKIP); - config.allowedGroupCiphers.set(GroupCipher.CCMP); - - config.allowedKeyManagement.set(KeyMgmt.WPA_PSK); - - config.allowedPairwiseCiphers.set(PairwiseCipher.CCMP); - config.allowedPairwiseCiphers.set(PairwiseCipher.TKIP); - - config.allowedProtocols.set(security.equals(WPA2) ? Protocol.RSN : Protocol.WPA); - - // If password is empty, it should be left untouched - if (!TextUtils.isEmpty(mPassword)) { - if (mPassword.length() == 64 && isHex(mPassword)) { - // Goes unquoted as hex - config.preSharedKey = mPassword; - } else { - // Goes quoted as ASCII - config.preSharedKey = convertToQuotedString(mPassword); - } - } - - } else if (security.equals(OPEN)) { - config.allowedKeyManagement.set(KeyMgmt.NONE); - } - } - - private static boolean isHexWepKey(String wepKey) { - final int len = wepKey.length(); - - // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?) - if (len != 10 && len != 26 && len != 58) { - return false; - } - - return isHex(wepKey); - } - - private static boolean isHex(String key) { - for (int i = key.length() - 1; i >= 0; i--) { - final char c = key.charAt(i); - if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) { - return false; - } - } - - return true; - } - - public void setCallback(AccessPointStateCallback callback) { - mCallback = callback; - } - - void blockRefresh() { - mBlockRefresh++; - } - - void unblockRefresh() { - if (--mBlockRefresh == 0 && mNeedsRefresh) { - requestRefresh(); - } - } - - private void requestRefresh() { - if (mBlockRefresh > 0) { - mNeedsRefresh = true; - return; - } - - if (mCallback != null) { - mCallback.refreshAccessPointState(); - } - - mNeedsRefresh = false; - } - - /** - * {@inheritDoc} - * @see #hashCode() - * @see #equals(Object) - */ - public int matches(int otherNetworkId, String otherBssid, String otherSsid, - String otherSecurity) { - - // Whenever this method is touched, please ensure #equals and #hashCode - // still work with the changes here! - - if (otherSsid == null) { - if (WifiLayer.LOGV) { - Log.w(TAG, "BSSID: " + otherBssid + ", SSID: " + otherSsid); - } - return MATCH_NONE; - } - - /* - * If we both have 'security' set, it must match (an open network still - * has 'security' set to OPEN) - */ - if (security != null && otherSecurity != null) { - if (!security.equals(otherSecurity)) { - return MATCH_NONE; - } - } - - // WifiConfiguration gives an empty bssid as a BSSID wildcard - if (TextUtils.isEmpty(otherBssid)) { - otherBssid = AccessPointState.BSSID_ANY; - } - - final boolean networkIdMatches = networkId == otherNetworkId; - if (!networkIdMatches && networkId != NETWORK_ID_ANY && otherNetworkId != NETWORK_ID_ANY) { - // Network IDs don't match (e.g., 1 & 2 or unset & 1) and neither is a wildcard - return MATCH_NONE; - } - - if (networkIdMatches && otherNetworkId != NETWORK_ID_NOT_SET - && otherNetworkId != NETWORK_ID_ANY) { - // Network ID matches (they're set to the same ID) - return MATCH_EXACT; - } - - // So now, network IDs aren't set or at least one is a wildcard - - final boolean bssidMatches = bssid.equals(otherBssid); - final boolean otherBssidIsWildcard = otherBssid.equals(BSSID_ANY); - if (bssidMatches && !otherBssidIsWildcard) { - // BSSID matches (and neither is a wildcard) - return MATCH_STRONG; - } - - if (!bssidMatches && !bssid.equals(BSSID_ANY) && !otherBssidIsWildcard) { - // BSSIDs don't match (e.g., 00:24:21:21:42:12 & 42:12:44:21:22:52) - // and neither is a wildcard - return MATCH_NONE; - } - - // So now, BSSIDs are both wildcards - - final boolean ssidMatches = ssid.equals(otherSsid); - if (ssidMatches) { - // SSID matches - return MATCH_WEAK; - } - - return MATCH_NONE; - } - - /** - * {@inheritDoc} - * @see #matches(int, String, String) - * @see #equals(Object) - */ - @Override - public int hashCode() { - // Two equal() objects must have same hashCode. - // With Wi-Fi, the broadest match is if two SSIDs are the same. The finer-grained matches - // imply this (for example, the same network IDs means the same WifiConfiguration which - // means the same SSID). - // See #matches for the exact matching algorithm we use. - return ssid != null ? ssid.hashCode() : 0; - } - - /** - * {@inheritDoc} - * @see #matches(int, String, String) - * @see #hashCode() - */ - @Override - public boolean equals(Object o) { - if (!o.getClass().equals(getClass())) { - return false; - } - - final AccessPointState other = (AccessPointState) o; - - // To see which conditions cause two AccessPointStates to be equal, see - // where #matches returns MATCH_WEAK or greater. - - return matches(other.networkId, other.bssid, other.ssid, other.security) >= MATCH_WEAK; - } - - public int matchesWifiConfiguration(WifiConfiguration wifiConfig) { - String security = getWifiConfigurationSecurity(wifiConfig); - return matches(wifiConfig.networkId, wifiConfig.BSSID, wifiConfig.SSID, security); - } - - String getSummarizedStatus() { - StringBuilder sb = mSummaryBuilder; - sb.delete(0, sb.length()); - - if (primary && status != null) { - buildSummary(sb, WifiStatus.getPrintable(mContext, status), true); - - } else if (!seen) { - buildSummary(sb, SUMMARY_NOT_IN_RANGE, true); - - // Remembered comes second in this case - if (!primary && configured) { - buildSummary(sb, SUMMARY_REMEMBERED, true); - } - - } else { - if (configured && disabled) { - // The connection failure overrides all in this case - return SUMMARY_CONNECTION_FAILED; - } - - // Remembered comes first in this case - if (!primary && configured) { - buildSummary(sb, SUMMARY_REMEMBERED, true); - } - - // If it is seen (and not the primary), show the security type - String verboseSecurity = getVerboseSecurity(); - if (verboseSecurity != null) { - buildSummary(sb, verboseSecurity, true); - } - } - - return sb.toString(); - } - - private String getVerboseSecurity() { - if (WEP.equals(security)) { - return LOCALIZED_VERBOSE_WEP; - } else if (WPA.equals(security)) { - return LOCALIZED_VERBOSE_WPA; - } else if (WPA2.equals(security)) { - return LOCALIZED_VERBOSE_WPA2; - } else if (OPEN.equals(security)) { - return LOCALIZED_VERBOSE_OPEN; - } else { - return null; - } - } - - private void buildSummary(StringBuilder sb, String string, boolean autoLowerCaseFirstLetter) { - if (sb.length() == 0) { - sb.append(string); - } else { - sb.append(", "); - if (autoLowerCaseFirstLetter) { - // Convert first letter to lowercase - sb.append(Character.toLowerCase(string.charAt(0))).append(string, 1, - string.length()); - } else { - sb.append(string); - } - } - } - - public int compareTo(AccessPointState other) { - // This ranks the states for displaying in the AP list, not for - // connecting to (wpa_supplicant does that using the WifiConfiguration's - // priority field). - - // Clarity > efficiency, of this logic: - int comparison; - - // Primary - comparison = (other.primary ? 1 : 0) - (primary ? 1 : 0); - if (comparison != 0) return comparison; - - // Currently seen (similar to, but not always the same as within range) - comparison = (other.seen ? 1 : 0) - (seen ? 1 : 0); - if (comparison != 0) return comparison; - - // Configured - comparison = (other.configured ? 1 : 0) - (configured ? 1 : 0); - if (comparison != 0) return comparison; - - if (!configured) { - // Neither are configured - - // Open network - comparison = (hasSecurity() ? 1 : 0) - (other.hasSecurity() ? 1 : 0); - if (comparison != 0) return comparison; - } - - // Signal strength - comparison = (int) (other.signalForSorting - signalForSorting); - if (comparison != 0) return comparison; - - // Alphabetical - return ssid.compareToIgnoreCase(other.ssid); - } - - public String toString() { - return ssid + " (" + bssid + ", " + networkId + ", " + super.toString() + ")"; - } - - /** Implement the Parcelable interface */ - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(bssid); - dest.writeInt(configured ? 1 : 0); - dest.writeInt(ipAddress); - dest.writeInt(linkSpeed); - dest.writeInt(networkId); - dest.writeInt(primary ? 1 : 0); - dest.writeInt(priority); - dest.writeInt(hiddenSsid ? 1 : 0); - dest.writeString(security); - dest.writeInt(seen ? 1 : 0); - dest.writeInt(disabled ? 1 : 0); - dest.writeInt(signal); - dest.writeString(ssid); - dest.writeString(status != null ? status.toString() : null); - dest.writeString(mPassword); - dest.writeInt(mConfigHadPassword ? 1 : 0); - dest.writeInt(mWepPasswordType); - } - - /** Implement the Parcelable interface */ - public int describeContents() { - return 0; - } - - /** Implement the Parcelable interface */ - public static final Creator<AccessPointState> CREATOR = - new Creator<AccessPointState>() { - public AccessPointState createFromParcel(Parcel in) { - AccessPointState state = new AccessPointState(); - state.bssid = in.readString(); - state.configured = in.readInt() == 1; - state.ipAddress = in.readInt(); - state.linkSpeed = in.readInt(); - state.networkId = in.readInt(); - state.primary = in.readInt() == 1; - state.priority = in.readInt(); - state.hiddenSsid = in.readInt() == 1; - state.security = in.readString(); - state.seen = in.readInt() == 1; - state.disabled = in.readInt() == 1; - state.signal = in.readInt(); - state.ssid = in.readString(); - String statusStr = in.readString(); - if (statusStr != null) { - state.status = NetworkInfo.DetailedState.valueOf(statusStr); - } - state.mPassword = in.readString(); - state.mConfigHadPassword = in.readInt() == 1; - state.mWepPasswordType = in.readInt(); - return state; - } - - public AccessPointState[] newArray(int size) { - return new AccessPointState[size]; - } - }; - - -} diff --git a/src/com/android/settings/wifi/AdvancedSettings.java b/src/com/android/settings/wifi/AdvancedSettings.java deleted file mode 100644 index 54aab4b..0000000 --- a/src/com/android/settings/wifi/AdvancedSettings.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.settings.wifi; - -import com.android.settings.R; - -import android.content.ContentResolver; -import android.net.wifi.WifiInfo; -import android.net.wifi.WifiManager; -import android.os.Bundle; -import android.preference.CheckBoxPreference; -import android.preference.EditTextPreference; -import android.preference.ListPreference; -import android.preference.Preference; -import android.preference.PreferenceActivity; -import android.provider.Settings; -import android.provider.Settings.System; -import android.text.TextUtils; -import android.view.KeyEvent; -import android.view.Menu; -import android.view.MenuItem; -import android.widget.Toast; - -public class AdvancedSettings extends PreferenceActivity - implements Preference.OnPreferenceChangeListener { - - private static final String KEY_MAC_ADDRESS = "mac_address"; - private static final String KEY_USE_STATIC_IP = "use_static_ip"; - private static final String KEY_NUM_CHANNELS = "num_channels"; - private static final String KEY_SLEEP_POLICY = "sleep_policy"; - - private String[] mSettingNames = { - System.WIFI_STATIC_IP, System.WIFI_STATIC_GATEWAY, System.WIFI_STATIC_NETMASK, - System.WIFI_STATIC_DNS1, System.WIFI_STATIC_DNS2 - }; - - private String[] mPreferenceKeys = { - "ip_address", "gateway", "netmask", "dns1", "dns2" - }; - - private CheckBoxPreference mUseStaticIpCheckBox; - - private static final int MENU_ITEM_SAVE = Menu.FIRST; - private static final int MENU_ITEM_CANCEL = Menu.FIRST + 1; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - addPreferencesFromResource(R.xml.wifi_advanced_settings); - - mUseStaticIpCheckBox = (CheckBoxPreference) findPreference(KEY_USE_STATIC_IP); - - for (int i = 0; i < mPreferenceKeys.length; i++) { - Preference preference = findPreference(mPreferenceKeys[i]); - preference.setOnPreferenceChangeListener(this); - } - } - - @Override - protected void onResume() { - super.onResume(); - - updateUi(); - initNumChannelsPreference(); - initSleepPolicyPreference(); - refreshMacAddress(); - } - - private void initNumChannelsPreference() { - ListPreference pref = (ListPreference) findPreference(KEY_NUM_CHANNELS); - pref.setOnPreferenceChangeListener(this); - - WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); - /* - * Generate the list of valid channel counts to show in the ListPreference. - * The values are numerical, so the only text to be localized is the - * "channel_word" resource. - */ - int[] validChannelCounts = wifiManager.getValidChannelCounts(); - if (validChannelCounts == null) { - Toast.makeText(this, R.string.wifi_setting_num_channels_error, - Toast.LENGTH_SHORT).show(); - return; - } - String[] entries = new String[validChannelCounts.length]; - String[] entryValues = new String[validChannelCounts.length]; - - for (int i = 0; i < validChannelCounts.length; i++) { - entryValues[i] = String.valueOf(validChannelCounts[i]); - entries[i] = getString(R.string.wifi_setting_num_channels_channel_phrase, - validChannelCounts[i]); - } - pref.setEntries(entries); - pref.setEntryValues(entryValues); - int numChannels = wifiManager.getNumAllowedChannels(); - if (numChannels >= 0) { - pref.setValue(String.valueOf(numChannels)); - } - } - - private void initSleepPolicyPreference() { - ListPreference pref = (ListPreference) findPreference(KEY_SLEEP_POLICY); - pref.setOnPreferenceChangeListener(this); - int value = Settings.System.getInt(getContentResolver(), - Settings.System.WIFI_SLEEP_POLICY,Settings. System.WIFI_SLEEP_POLICY_DEFAULT); - pref.setValue(String.valueOf(value)); - } - - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - - if (keyCode == KeyEvent.KEYCODE_BACK) { - updateSettingsProvider(); - } - - return super.onKeyDown(keyCode, event); - } - - public boolean onPreferenceChange(Preference preference, Object newValue) { - String key = preference.getKey(); - if (key == null) return true; - - if (key.equals(KEY_NUM_CHANNELS)) { - try { - int numChannels = Integer.parseInt((String) newValue); - WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); - if (!wifiManager.setNumAllowedChannels(numChannels)) { - Toast.makeText(this, R.string.wifi_setting_num_channels_error, - Toast.LENGTH_SHORT).show(); - } - } catch (NumberFormatException e) { - Toast.makeText(this, R.string.wifi_setting_num_channels_error, - Toast.LENGTH_SHORT).show(); - return false; - } - - } else if (key.equals(KEY_SLEEP_POLICY)) { - try { - Settings.System.putInt(getContentResolver(), - Settings.System.WIFI_SLEEP_POLICY, Integer.parseInt(((String) newValue))); - } catch (NumberFormatException e) { - Toast.makeText(this, R.string.wifi_setting_sleep_policy_error, - Toast.LENGTH_SHORT).show(); - return false; - } - - } else { - String value = (String) newValue; - - if (!isIpAddress(value)) { - Toast.makeText(this, R.string.wifi_ip_settings_invalid_ip, Toast.LENGTH_LONG).show(); - return false; - } - - preference.setSummary(value); - } - - return true; - } - - private boolean isIpAddress(String value) { - - int start = 0; - int end = value.indexOf('.'); - int numBlocks = 0; - - while (start < value.length()) { - - if (end == -1) { - end = value.length(); - } - - try { - int block = Integer.parseInt(value.substring(start, end)); - if ((block > 255) || (block < 0)) { - return false; - } - } catch (NumberFormatException e) { - return false; - } - - numBlocks++; - - start = end + 1; - end = value.indexOf('.', start); - } - - return numBlocks == 4; - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - - menu.add(0, MENU_ITEM_SAVE, 0, R.string.wifi_ip_settings_menu_save) - .setIcon(android.R.drawable.ic_menu_save); - - menu.add(0, MENU_ITEM_CANCEL, 0, R.string.wifi_ip_settings_menu_cancel) - .setIcon(android.R.drawable.ic_menu_close_clear_cancel); - - return super.onCreateOptionsMenu(menu); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - - switch (item.getItemId()) { - - case MENU_ITEM_SAVE: - updateSettingsProvider(); - finish(); - return true; - - case MENU_ITEM_CANCEL: - finish(); - return true; - } - - return super.onOptionsItemSelected(item); - } - - private void updateUi() { - ContentResolver contentResolver = getContentResolver(); - - mUseStaticIpCheckBox.setChecked(System.getInt(contentResolver, - System.WIFI_USE_STATIC_IP, 0) != 0); - - for (int i = 0; i < mSettingNames.length; i++) { - EditTextPreference preference = (EditTextPreference) findPreference(mPreferenceKeys[i]); - String settingValue = System.getString(contentResolver, mSettingNames[i]); - preference.setText(settingValue); - preference.setSummary(settingValue); - } - } - - private void updateSettingsProvider() { - ContentResolver contentResolver = getContentResolver(); - - System.putInt(contentResolver, System.WIFI_USE_STATIC_IP, - mUseStaticIpCheckBox.isChecked() ? 1 : 0); - - for (int i = 0; i < mSettingNames.length; i++) { - EditTextPreference preference = (EditTextPreference) findPreference(mPreferenceKeys[i]); - System.putString(contentResolver, mSettingNames[i], preference.getText()); - } - } - - private void refreshMacAddress() { - WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); - WifiInfo wifiInfo = wifiManager.getConnectionInfo(); - - Preference wifiMacAddressPref = findPreference(KEY_MAC_ADDRESS); - String macAddress = wifiInfo == null ? null : wifiInfo.getMacAddress(); - wifiMacAddressPref.setSummary(!TextUtils.isEmpty(macAddress) ? macAddress - : getString(R.string.status_unavailable)); - } - -} diff --git a/src/com/android/settings/wifi/WifiEnabler.java b/src/com/android/settings/wifi/WifiEnabler.java deleted file mode 100644 index 88cfe06..0000000 --- a/src/com/android/settings/wifi/WifiEnabler.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.settings.wifi; - -import static android.net.wifi.WifiManager.WIFI_STATE_DISABLED; -import static android.net.wifi.WifiManager.WIFI_STATE_DISABLING; -import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED; -import static android.net.wifi.WifiManager.WIFI_STATE_ENABLING; -import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN; - -import com.android.settings.R; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.net.NetworkInfo; -import android.net.wifi.WifiManager; -import android.preference.Preference; -import android.preference.CheckBoxPreference; -import android.text.TextUtils; -import android.util.Config; -import android.util.Log; - -public class WifiEnabler implements Preference.OnPreferenceChangeListener { - - private static final boolean LOCAL_LOGD = Config.LOGD || WifiLayer.LOGV; - private static final String TAG = "SettingsWifiEnabler"; - - private final Context mContext; - private final WifiManager mWifiManager; - private final CheckBoxPreference mWifiCheckBoxPref; - private final CharSequence mOriginalSummary; - - private final IntentFilter mWifiStateFilter; - private final BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() { - - @Override - public void onReceive(Context context, Intent intent) { - if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { - handleWifiStateChanged( - intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WIFI_STATE_UNKNOWN), - intent.getIntExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, - WIFI_STATE_UNKNOWN)); - } else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { - handleNetworkStateChanged( - (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO)); - } - } - }; - - public WifiEnabler(Context context, WifiManager wifiManager, - CheckBoxPreference wifiCheckBoxPreference) { - mContext = context; - mWifiCheckBoxPref = wifiCheckBoxPreference; - mWifiManager = wifiManager; - - mOriginalSummary = wifiCheckBoxPreference.getSummary(); - wifiCheckBoxPreference.setPersistent(false); - - mWifiStateFilter = new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION); - mWifiStateFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); - } - - public void resume() { - int state = mWifiManager.getWifiState(); - // This is the widget enabled state, not the preference toggled state - mWifiCheckBoxPref.setEnabled(state == WIFI_STATE_ENABLED || state == WIFI_STATE_DISABLED - || state == WIFI_STATE_UNKNOWN); - - mContext.registerReceiver(mWifiStateReceiver, mWifiStateFilter); - mWifiCheckBoxPref.setOnPreferenceChangeListener(this); - } - - public void pause() { - mContext.unregisterReceiver(mWifiStateReceiver); - mWifiCheckBoxPref.setOnPreferenceChangeListener(null); - } - - public boolean onPreferenceChange(Preference preference, Object value) { - // Turn on/off Wi-Fi - setWifiEnabled((Boolean) value); - - // Don't update UI to opposite state until we're sure - return false; - } - - private void setWifiEnabled(final boolean enable) { - // Disable button - mWifiCheckBoxPref.setEnabled(false); - - if (!mWifiManager.setWifiEnabled(enable)) { - mWifiCheckBoxPref.setSummary(enable ? R.string.error_starting : R.string.error_stopping); - } - } - - private void handleWifiStateChanged(int wifiState, int previousWifiState) { - - if (LOCAL_LOGD) { - Log.d(TAG, "Received wifi state changed from " - + getHumanReadableWifiState(previousWifiState) + " to " - + getHumanReadableWifiState(wifiState)); - } - - if (wifiState == WIFI_STATE_DISABLED || wifiState == WIFI_STATE_ENABLED) { - mWifiCheckBoxPref.setChecked(wifiState == WIFI_STATE_ENABLED); - mWifiCheckBoxPref - .setSummary(wifiState == WIFI_STATE_DISABLED ? mOriginalSummary : null); - - mWifiCheckBoxPref.setEnabled(isEnabledByDependency()); - - } else if (wifiState == WIFI_STATE_DISABLING || wifiState == WIFI_STATE_ENABLING) { - mWifiCheckBoxPref.setSummary(wifiState == WIFI_STATE_ENABLING ? R.string.wifi_starting - : R.string.wifi_stopping); - - } else if (wifiState == WIFI_STATE_UNKNOWN) { - int message = R.string.wifi_error; - if (previousWifiState == WIFI_STATE_ENABLING) message = R.string.error_starting; - else if (previousWifiState == WIFI_STATE_DISABLING) message = R.string.error_stopping; - - mWifiCheckBoxPref.setChecked(false); - mWifiCheckBoxPref.setSummary(message); - mWifiCheckBoxPref.setEnabled(true); - } - } - - private void handleNetworkStateChanged(NetworkInfo networkInfo) { - - if (LOCAL_LOGD) { - Log.d(TAG, "Received network state changed to " + networkInfo); - } - - if (mWifiManager.isWifiEnabled()) { - String summary = WifiStatus.getStatus(mContext, - mWifiManager.getConnectionInfo().getSSID(), networkInfo.getDetailedState()); - mWifiCheckBoxPref.setSummary(summary); - } - } - - private boolean isEnabledByDependency() { - Preference dep = getDependencyPreference(); - if (dep == null) { - return true; - } - - return !dep.shouldDisableDependents(); - } - - private Preference getDependencyPreference() { - String depKey = mWifiCheckBoxPref.getDependency(); - if (TextUtils.isEmpty(depKey)) { - return null; - } - - return mWifiCheckBoxPref.getPreferenceManager().findPreference(depKey); - } - - private static String getHumanReadableWifiState(int wifiState) { - switch (wifiState) { - case WIFI_STATE_DISABLED: - return "Disabled"; - case WIFI_STATE_DISABLING: - return "Disabling"; - case WIFI_STATE_ENABLED: - return "Enabled"; - case WIFI_STATE_ENABLING: - return "Enabling"; - case WIFI_STATE_UNKNOWN: - return "Unknown"; - default: - return "Some other state!"; - } - } -} diff --git a/src/com/android/settings/wifi/WifiLayer.java b/src/com/android/settings/wifi/WifiLayer.java deleted file mode 100644 index b0857d2..0000000 --- a/src/com/android/settings/wifi/WifiLayer.java +++ /dev/null @@ -1,1302 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.settings.wifi; - -import static android.net.wifi.WifiManager.WIFI_STATE_DISABLED; -import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED; - -import com.android.settings.R; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.net.NetworkInfo; -import android.net.NetworkInfo.DetailedState; -import android.net.NetworkInfo.State; -import android.net.wifi.ScanResult; -import android.net.wifi.SupplicantState; -import android.net.wifi.WifiConfiguration; -import android.net.wifi.WifiInfo; -import android.net.wifi.WifiManager; -import android.os.Handler; -import android.os.Message; -import android.provider.Settings; -import android.text.TextUtils; -import android.util.Config; -import android.util.Log; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -/** - * Helper class for abstracting Wi-Fi. - * <p> - * Client must call {@link #onCreate()}, {@link #onCreatedCallback()}, - * {@link #onPause()}, {@link #onResume()}. - */ -public class WifiLayer { - - private static final String TAG = "SettingsWifiLayer"; - static final boolean LOGV = false || Config.LOGV; - - //============================ - // Other member variables - //============================ - - private Context mContext; - private Callback mCallback; - - static final int MESSAGE_ATTEMPT_SCAN = 1; - private Handler mHandler = new MyHandler(); - - //============================ - // Wifi member variables - //============================ - - private WifiManager mWifiManager; - private IntentFilter mIntentFilter; - private List<AccessPointState> mApScanList = new ArrayList<AccessPointState>(); - private List<AccessPointState> mApOtherList = new ArrayList<AccessPointState>(); - private AccessPointState mCurrentPrimaryAp; - - /** The last access point that we were authenticating with. */ - private AccessPointState mLastAuthenticatingAp; - - /** The delay between scans when we're continually scanning. */ - private static final int CONTINUOUS_SCAN_DELAY_MS = 6000; - /** On failure, the maximum retries for scanning. */ - private static final int SCAN_MAX_RETRY = 5; - /** On failure, the delay between each scan retry. */ - private static final int SCAN_RETRY_DELAY_MS = 1000; - /** On failure, the number of retries so far. */ - private int mScanRetryCount = 0; - /** - * Whether we're currently obtaining an address. Continuous scanning will be - * disabled in this state. - */ - private boolean mIsObtainingAddress; - - /** - * See {@link android.provider.Settings.Secure#WIFI_NUM_OPEN_NETWORKS_KEPT}. - */ - private int WIFI_NUM_OPEN_NETWORKS_KEPT; - /** - * Once the highest priority exceeds this value, all networks will be - * wrapped around starting at 0. This is so another client of the Wi-Fi - * API can have access points that aren't managed by us. (If the other - * client wants lower-priority access points than ours, it can use negative - * priority.) - */ - private static final int HIGHEST_PRIORITY_MAX_VALUE = 99999; - /** - * Never access directly, only the related methods should. - */ - private int mNextHighestPriority; - - /** - * This is used to track when the user wants to connect to a specific AP. We - * disable all other APs, set this to true, and let wpa_supplicant connect. - * Once we get a network state change, we re-enable the rest of them. - */ - private boolean mReenableApsOnNetworkStateChange = false; - - /** - * The current supplicant state, as broadcasted. - */ - private SupplicantState mCurrentSupplicantState; - - //============================ - // Inner classes - //============================ - - interface Callback { - void onError(int messageResId); - - /** - * Called when an AP is added or removed. - * - * @param ap The AP. - * @param added {@code true} if added, {@code false} if removed. - */ - void onAccessPointSetChanged(AccessPointState ap, boolean added); - - /** - * Called when the scanning status changes. - * - * @param started {@code true} if the scanning just started, - * {@code false} if it just ended. - */ - void onScanningStatusChanged(boolean started); - - /** - * Called when the access points should be enabled or disabled. This is - * called from both wpa_supplicant being connected/disconnected and Wi-Fi - * being enabled/disabled. - * - * @param enabled {@code true} if they should be enabled, {@code false} - * if they should be disabled. - */ - void onAccessPointsStateChanged(boolean enabled); - - /** - * Called when there is trouble authenticating and the retry-password - * dialog should be shown. - * - * @param ap The access point. - */ - void onRetryPassword(AccessPointState ap); - } - - private BroadcastReceiver mReceiver = new BroadcastReceiver() { - - @Override - public void onReceive(Context context, Intent intent) { - final String action = intent.getAction(); - if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { - handleNetworkStateChanged( - (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO), - intent.getStringExtra(WifiManager.EXTRA_BSSID)); - } else if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { - handleScanResultsAvailable(); - } else if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) { - handleSupplicantConnectionChanged( - intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)); - } else if (action.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) { - handleSupplicantStateChanged( - (SupplicantState) intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE), - intent.hasExtra(WifiManager.EXTRA_SUPPLICANT_ERROR), - intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 0)); - } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { - handleWifiStateChanged(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, - WifiManager.WIFI_STATE_UNKNOWN)); - } else if (action.equals(WifiManager.RSSI_CHANGED_ACTION)) { - handleSignalChanged(intent.getIntExtra(WifiManager.EXTRA_NEW_RSSI, 0)); - } else if (action.equals(WifiManager.NETWORK_IDS_CHANGED_ACTION)) { - handleNetworkIdsChanged(); - } - } - }; - - /** - * If using this class, make sure to call the callbacks of this class, such - * as {@link #onCreate()}, {@link #onCreatedCallback()}, - * {@link #onPause()}, {@link #onResume()}. - * - * @param context The context. - * @param callback The interface that will be invoked when events from this - * class are generated. - */ - public WifiLayer(Context context, Callback callback) { - mContext = context; - mCallback = callback; - } - - //============================ - // Lifecycle - //============================ - - /** - * The client MUST call this. - * <p> - * This shouldn't have any dependency on the callback. - */ - public void onCreate() { - mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); - - mIntentFilter = new IntentFilter(); - mIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); - mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); - mIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION); - mIntentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); - mIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); - mIntentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION); - mIntentFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION); - - WIFI_NUM_OPEN_NETWORKS_KEPT = Settings.Secure.getInt(mContext.getContentResolver(), - Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT, 10); - } - - /** - * The client MUST call this. - * <p> - * Callback is ready, this can do whatever it wants with it. - */ - public void onCreatedCallback() { - if (isWifiEnabled()) { - refreshAll(false); - } - } - - /** - * The client MUST call this. - * - * @see android.app.Activity#onResume - */ - public void onResume() { - mContext.registerReceiver(mReceiver, mIntentFilter); - - if (isWifiEnabled()) { - // Kick start the continual scan - queueContinuousScan(); - } - } - - /** - * The client MUST call this. - * - * @see android.app.Activity#onPause - */ - public void onPause() { - mContext.unregisterReceiver(mReceiver); - - attemptReenableAllAps(); - - removeFutureScans(); - } - - //============================ - // "Public" API - //============================ - - /** - * Returns an AccessPointState instance (that we track locally in WifiLayer) - * for the given state. First, we check if we track the given instance. If - * not, we find an equal AccessPointState instance that we track. - * - * @param state An AccessPointState instance that does not necessarily have - * to be one that this WifiLayer class tracks. For example, it - * could be the result of unparceling. - * @return An AccessPointState instance that this WifiLayer class tracks. - */ - public AccessPointState getWifiLayerApInstance(AccessPointState state) { - synchronized (this) { - - if (hasApInstanceLocked(state)) { - return state; - } - - return findApLocked(state.networkId, state.bssid, state.ssid, state.security); - } - } - - /** - * Connects to the network, and creates the Wi-Fi API config if necessary. - * - * @param state The state of the network to connect to. This MUST be an - * instance that was given to you by this class. If you - * constructed the instance yourself (for example, after - * unparceling it), you should use - * {@link #getWifiLayerApInstance(AccessPointState)}. - * @return Whether the operation was successful. - */ - public boolean connectToNetwork(AccessPointState state) { - if (LOGV) { - Log.v(TAG, "Connecting to " + state); - } - - // Need WifiConfiguration for the AP - WifiConfiguration config = findConfiguredNetwork(state); - - if (LOGV) { - Log.v(TAG, " Found configured network " + config); - } - - if (config == null) { - /* - * Connecting for the first time, need to create it. We will enable - * and save it below (when we set priority). - */ - config = addConfiguration(state, 0); - - if (config == null) { - Log.e(TAG, "Config is still null, even after attempting to add it."); - error(R.string.error_connecting); - return false; - } - - /* - * We could reload the configured networks, but instead just - * shortcut and add this state to our list in memory. - */ - ensureTrackingState(state); - } else { - // Make sure the configuration has the latest from the state - state.updateWifiConfiguration(config); - } - - // Enable this network before we save to storage - if (!managerEnableNetwork(state, false)) { - Log.e(TAG, "Could not enable network ID " + state.networkId); - error(R.string.error_connecting); - return false; - } - - /* - * Give it highest priority, this could cause a network ID change, so do - * it after any modifications to the network we're connecting to - */ - setHighestPriorityStateAndSave(state, config); - - /* - * We force supplicant to connect to this network by disabling the - * others. We do this AFTER we save above so this disabled flag isn't - * persisted. - */ - mReenableApsOnNetworkStateChange = true; - if (!managerEnableNetwork(state, true)) { - Log.e(TAG, "Could not enable network ID " + state.networkId); - error(R.string.error_connecting); - return false; - } - - if (LOGV) { - Log.v(TAG, " Enabled network " + state.networkId); - } - - if (mCurrentSupplicantState == SupplicantState.DISCONNECTED || - mCurrentSupplicantState == SupplicantState.SCANNING) { - mWifiManager.reconnect(); - } - - // Check for too many configured open networks - if (!state.hasSecurity()) { - checkForExcessOpenNetworks(); - } - - return true; - } - - /** - * Saves a network, and creates the Wi-Fi API config if necessary. - * - * @param state The state of the network to save. If you constructed the - * instance yourself (for example, after unparceling it), you - * should use {@link #getWifiLayerApInstance(AccessPointState)}. - * @return Whether the operation was successful. - */ - public boolean saveNetwork(AccessPointState state) { - WifiConfiguration config = findConfiguredNetwork(state); - - if (config == null) { - // if the user is adding a new network, assume that it is hidden - state.setHiddenSsid(true); - - config = addConfiguration(state, ADD_CONFIGURATION_ENABLE); - - if (config == null) { - Log.e(TAG, "Could not save configuration, call to addConfiguration failed."); - error(R.string.error_saving); - return false; - } - - } else { - state.updateWifiConfiguration(config); - if (mWifiManager.updateNetwork(config) == -1) { - Log.e(TAG, "Could not update configuration, call to WifiManager failed."); - error(R.string.error_saving); - return false; - } - } - - // Successfully added network, go ahead and persist - if (!managerSaveConfiguration()) { - Log.e(TAG, "Could not save configuration, call to WifiManager failed."); - error(R.string.error_saving); - return false; - } - - /* - * We could reload the configured networks, but instead just shortcut - * and add this state to our list in memory - */ - ensureTrackingState(state); - - return true; - } - - /** - * Forgets a network. - * - * @param state The state of the network to forget. If you constructed the - * instance yourself (for example, after unparceling it), you - * should use {@link #getWifiLayerApInstance(AccessPointState)}. - * @return Whether the operation was succesful. - */ - public boolean forgetNetwork(AccessPointState state) { - if (!state.configured) { - Log.w(TAG, "Inconsistent state: Forgetting a network that is not configured."); - return true; - } - - int oldNetworkId = state.networkId; - state.forget(); - - if (!state.seen) { - // If it is not seen, it should be removed from the UI - removeApFromUi(state); - } - - synchronized (this) { - mApOtherList.remove(state); - // It should not be removed from the scan list, since if it was - // there that means it's still seen - } - - if (!mWifiManager.removeNetwork(oldNetworkId)) { - Log.e(TAG, "Removing network " + state.ssid + " (network ID " + oldNetworkId + - ") failed."); - return false; - } - - if (!managerSaveConfiguration()) { - error(R.string.error_saving); - return false; - } - - return true; - } - - /** - * This ensures this class is tracking the given state. This means it is in - * our list of access points, either in the scanned list or in the - * remembered list. - * - * @param state The state that will be checked for tracking, and if not - * tracking will be added to the remembered list in memory. - */ - private void ensureTrackingState(AccessPointState state) { - synchronized (this) { - if (hasApInstanceLocked(state)) { - return; - } - - mApOtherList.add(state); - } - } - - /** - * Attempts to scan networks. This has a retry mechanism. - */ - public void attemptScan() { - - // Remove any future scans since we're scanning right now - removeFutureScans(); - - if (!mWifiManager.isWifiEnabled()) return; - - if (!mWifiManager.startScan()) { - postAttemptScan(); - } else { - mScanRetryCount = 0; - } - } - - private void queueContinuousScan() { - mHandler.removeMessages(MESSAGE_ATTEMPT_SCAN); - - if (!mIsObtainingAddress) { - // Don't do continuous scan while in obtaining IP state - mHandler.sendEmptyMessageDelayed(MESSAGE_ATTEMPT_SCAN, CONTINUOUS_SCAN_DELAY_MS); - } - } - - private void removeFutureScans() { - mHandler.removeMessages(MESSAGE_ATTEMPT_SCAN); - } - - public boolean isWifiEnabled() { - return mWifiManager.isWifiEnabled(); - } - - public void error(int messageResId) { - Log.e(TAG, mContext.getResources().getString(messageResId)); - - if (mCallback != null) { - mCallback.onError(messageResId); - } - } - - //============================ - // Wifi logic - //============================ - - private void refreshAll(boolean attemptScan) { - loadConfiguredAccessPoints(); - refreshStatus(); - - if (attemptScan) { - attemptScan(); - } - } - - private void postAttemptScan() { - onScanningStarted(); - - if (++mScanRetryCount < SCAN_MAX_RETRY) { - // Just in case, remove previous ones first - removeFutureScans(); - mHandler.sendEmptyMessageDelayed(MESSAGE_ATTEMPT_SCAN, SCAN_RETRY_DELAY_MS); - } else { - // Show an error once we run out of attempts - error(R.string.error_scanning); - onScanningEnded(); - } - } - - private void onScanningStarted() { - if (mCallback != null) { - mCallback.onScanningStatusChanged(true); - } - } - - private void onScanningEnded() { - queueContinuousScan(); - - if (mCallback != null) { - mCallback.onScanningStatusChanged(false); - } - } - - private void clearApLists() { - List<AccessPointState> accessPoints = new ArrayList<AccessPointState>(); - - synchronized(this) { - // Clear the logic's list of access points - accessPoints.addAll(mApScanList); - accessPoints.addAll(mApOtherList); - mApScanList.clear(); - mApOtherList.clear(); - } - - for (int i = accessPoints.size() - 1; i >= 0; i--) { - removeApFromUi(accessPoints.get(i)); - } - } - - private boolean managerSaveConfiguration() { - boolean retValue = mWifiManager.saveConfiguration(); - - /* - * We need to assume the network IDs have changed, so handle this. Note: - * we also have a receiver on the broadcast intent in case another wifi - * framework client caused the change. In this case, we will handle the - * possible network ID change twice (but it's not too costly). - */ - handleNetworkIdsChanged(); - - return retValue; - } - - private boolean managerEnableNetwork(AccessPointState state, boolean disableOthers) { - if (!mWifiManager.enableNetwork(state.networkId, disableOthers)) { - return false; - } - - // Enabling was successful, make sure the state is not disabled - state.setDisabled(false); - - return true; - } - - private static final int ADD_CONFIGURATION_ENABLE = 1; - private static final int ADD_CONFIGURATION_SAVE = 2; - private WifiConfiguration addConfiguration(AccessPointState state, int flags) { - // Create and add - WifiConfiguration config = new WifiConfiguration(); - - state.updateWifiConfiguration(config); - - final int networkId = mWifiManager.addNetwork(config); - if (networkId == -1) { - return null; - } - - state.setNetworkId(networkId); - state.setConfigured(true); - - // If we should, then enable it, since it comes disabled by default - if ((flags & ADD_CONFIGURATION_ENABLE) != 0 - && !managerEnableNetwork(state, false)) { - return null; - } - - // If we should, then save it - if ((flags & ADD_CONFIGURATION_SAVE) != 0 && !managerSaveConfiguration()) { - return null; - } - - if (mCallback != null) { - mCallback.onAccessPointSetChanged(state, true); - } - - return config; - } - - private WifiConfiguration findConfiguredNetwork(AccessPointState state) { - final List<WifiConfiguration> wifiConfigs = getConfiguredNetworks(); - - for (int i = wifiConfigs.size() - 1; i >= 0; i--) { - final WifiConfiguration wifiConfig = wifiConfigs.get(i); - if (state.matchesWifiConfiguration(wifiConfig) >= AccessPointState.MATCH_WEAK) { - return wifiConfig; - } - } - - return null; - } - - private List<WifiConfiguration> getConfiguredNetworks() { - final List<WifiConfiguration> wifiConfigs = mWifiManager.getConfiguredNetworks(); - return wifiConfigs; - } - - /** - * Must call while holding the lock for the list, which is usually the - * WifiLayer instance. - */ - private static AccessPointState findApLocked(List<AccessPointState> list, int networkId, - String bssid, String ssid, String security) { - AccessPointState ap; - for (int i = list.size() - 1; i >= 0; i--) { - ap = list.get(i); - if (ap.matches(networkId, bssid, ssid, security) >= AccessPointState.MATCH_WEAK) { - return ap; - } - } - - return null; - } - - /** - * Must call while holding the lock for the lists, which is usually this - * WifiLayer instance. - */ - private AccessPointState findApLocked(int networkId, String bssid, String ssid, - String security) { - AccessPointState ap = findApLocked(mApScanList, networkId, bssid, ssid, security); - if (ap == null) { - ap = findApLocked(mApOtherList, networkId, bssid, ssid, security); - } - return ap; - } - - /** - * Returns whether we have the exact instance of the access point state - * given. This is useful in cases where an AccessPointState has been - * parceled by the client and the client is attempting to use it to - * connect/forget/save. - * <p> - * Must call while holding the lock for the lists, which is usually this - * WifiLayer instance. - */ - private boolean hasApInstanceLocked(AccessPointState state) { - - for (int i = mApScanList.size() - 1; i >= 0; i--) { - if (mApScanList.get(i) == state) { - return true; - } - } - - for (int i = mApOtherList.size() - 1; i >= 0; i--) { - if (mApOtherList.get(i) == state) { - return true; - } - } - - return false; - } - - private void loadConfiguredAccessPoints() { - final List<WifiConfiguration> configs = getConfiguredNetworks(); - - for (int i = configs.size() - 1; i >= 0; i--) { - final WifiConfiguration config = configs.get(i); - - AccessPointState ap; - synchronized(this) { - ap = findApLocked(config.networkId, config.BSSID, config.SSID, - AccessPointState.getWifiConfigurationSecurity(config)); - - if (ap != null) { - // We already know about this one - continue; - } - - ap = new AccessPointState(mContext); - ap.updateFromWifiConfiguration(config); - if (LOGV) Log.v(TAG, "Created " + ap + " in loadConfiguredAccessPoints"); - mApOtherList.add(ap); - } - - // Make sure our next highest priority is greater than this - checkNextHighestPriority(ap.priority); - - if (mCallback != null) { - mCallback.onAccessPointSetChanged(ap, true); - } - } - } - - private AccessPointState getCurrentAp() { - final WifiInfo wifiInfo = mWifiManager.getConnectionInfo(); - - String ssid = wifiInfo.getSSID(); - if (ssid != null) { - /* - * We pass null for security since we have a network ID (i.e., it's - * not a wildcard), and rely on it matching. - */ - return findApLocked(wifiInfo.getNetworkId(), wifiInfo.getBSSID(), ssid, null); - } else { - return null; - } - } - - private void setPrimaryAp(AccessPointState ap) { - synchronized (this) { - // Unset other - if (mCurrentPrimaryAp != null) { - mCurrentPrimaryAp.setPrimary(false); - } - - mCurrentPrimaryAp = ap; - } - - if (ap != null) { - ap.setPrimary(true); - } - } - - private void attemptReenableAllAps() { - if (mReenableApsOnNetworkStateChange) { - mReenableApsOnNetworkStateChange = false; - enableAllAps(); - } - } - - private void enableAllAps() { - synchronized(this) { - if (LOGV) { - Log.v(TAG, " Enabling all APs"); - } - - enableApsLocked(mApOtherList); - enableApsLocked(mApScanList); - } - } - - private void enableApsLocked(List<AccessPointState> apList) { - for (int i = apList.size() - 1; i >= 0; i--) { - AccessPointState state = apList.get(i); - int networkId = state.networkId; - if (networkId != AccessPointState.NETWORK_ID_NOT_SET && - networkId != AccessPointState.NETWORK_ID_ANY) { - managerEnableNetwork(state, false); - } - } - } - - private void removeApFromUi(AccessPointState ap) { - if (mCallback != null) { - mCallback.onAccessPointSetChanged(ap, false); - } - } - - /** - * Sets the access point state to the highest priority. - * <p> - * If you have a list of configured networks from WifiManager, you probably - * shouldn't call this until you're done traversing the list. - * - * @param state The state to set as the highest priority. - * @param reusableConfiguration An optional WifiConfiguration that will be - * given to the WifiManager as updated data for the network ID. - * This will be filled with the new priority. - * @return Whether the operation was successful. - */ - private boolean setHighestPriorityStateAndSave(AccessPointState state, - WifiConfiguration reusableConfiguration) { - - if (!isConsideredForHighestPriority(state)) { - Log.e(TAG, - "Could not set highest priority on state because state is not being considered."); - return false; - } - - if (reusableConfiguration == null) { - reusableConfiguration = new WifiConfiguration(); - } - - int oldPriority = reusableConfiguration.priority; - reusableConfiguration.priority = getNextHighestPriority(); - reusableConfiguration.networkId = state.networkId; - - if (mWifiManager.updateNetwork(reusableConfiguration) == -1) { - // Rollback priority - reusableConfiguration.priority = oldPriority; - Log.e(TAG, - "Could not set highest priority on state because updating the supplicant network failed."); - return false; - } - - if (!managerSaveConfiguration()) { - reusableConfiguration.priority = oldPriority; - Log.e(TAG, - "Could not set highest priority on state because saving config failed."); - return false; - } - - state.priority = reusableConfiguration.priority; - - if (LOGV) { - Log.v(TAG, " Set highest priority to " - + state.priority + " from " + oldPriority); - } - - return true; - } - - /** - * Makes sure the next highest priority is larger than the given priority. - */ - private void checkNextHighestPriority(int priority) { - if (priority > HIGHEST_PRIORITY_MAX_VALUE || priority < 0) { - // This is a priority that we aren't managing - return; - } - - if (mNextHighestPriority <= priority) { - mNextHighestPriority = priority + 1; - } - } - - /** - * Checks if there are too many open networks, and removes the excess ones. - */ - private void checkForExcessOpenNetworks() { - synchronized(this) { - ArrayList<AccessPointState> allAps = getApsSortedByPriorityLocked(); - - // Walk from highest to lowest priority - int openConfiguredCount = 0; - for (int i = allAps.size() - 1; i >= 0; i--) { - AccessPointState state = allAps.get(i); - if (state.configured && !state.hasSecurity()) { - openConfiguredCount++; - if (openConfiguredCount > WIFI_NUM_OPEN_NETWORKS_KEPT) { - // Remove this network - forgetNetwork(state); - } - } - } - } - } - - private boolean isConsideredForHighestPriority(AccessPointState state) { - return state.configured && state.networkId != AccessPointState.NETWORK_ID_ANY && - state.networkId != AccessPointState.NETWORK_ID_NOT_SET; - } - - /** - * Gets the next highest priority. If this value is larger than the max, - * shift all the priorities so the lowest starts at 0. - * <p> - * Only - * {@link #setHighestPriorityStateAndSave(AccessPointState, WifiConfiguration)} - * should call this. - * - * @return The next highest priority to use. - */ - private int getNextHighestPriority() { - if (mNextHighestPriority > HIGHEST_PRIORITY_MAX_VALUE) { - shiftPriorities(); - } - - return mNextHighestPriority++; - } - - /** - * Shift all the priorities so the lowest starts at 0. - * - * @return Whether the operation was successful. - */ - private boolean shiftPriorities() { - synchronized(this) { - - ArrayList<AccessPointState> allAps = getApsSortedByPriorityLocked(); - - // Re-usable WifiConfiguration for setting priority - WifiConfiguration updatePriorityConfig = new WifiConfiguration(); - - // Set new priorities - mNextHighestPriority = 0; - int size = allAps.size(); - for (int i = 0; i < size; i++) { - AccessPointState state = allAps.get(i); - - if (!isConsideredForHighestPriority(state)) { - continue; - } - - if (!setHighestPriorityStateAndSave(state, updatePriorityConfig)) { - Log.e(TAG, - "Could not shift priorities because setting the new priority failed."); - return false; - } - } - - return true; - } - } - - private ArrayList<AccessPointState> getApsSortedByPriorityLocked() { - // Get all of the access points we have - ArrayList<AccessPointState> allAps = new ArrayList<AccessPointState>(mApScanList.size() - + mApOtherList.size()); - allAps.addAll(mApScanList); - allAps.addAll(mApOtherList); - - // Sort them based on priority - Collections.sort(allAps, new Comparator<AccessPointState>() { - public int compare(AccessPointState object1, AccessPointState object2) { - return object1.priority - object2.priority; - } - }); - - return allAps; - } - - //============================ - // Status related - //============================ - - private void refreshStatus() { - refreshStatus(null, null); - } - - private void refreshStatus(AccessPointState ap, NetworkInfo.DetailedState detailedState) { - final WifiInfo wifiInfo = mWifiManager.getConnectionInfo(); - if (detailedState == null) { - detailedState = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState()); - } - - if (ap == null && WifiStatus.isLiveConnection(detailedState)) { - /* - * We pass null for security since we have a network ID (i.e., it's - * not a wildcard), and rely on it matching. - */ - ap = findApLocked(wifiInfo.getNetworkId(), wifiInfo.getBSSID(), wifiInfo - .getSSID(), null); - } - - if (ap != null) { - ap.blockRefresh(); - - // Let the AP get the latest info from the WifiInfo - ap.updateFromWifiInfo(wifiInfo, detailedState); - - // The detailed state from the Intent has more states than the WifiInfo's detailed - // state can have (for example, DHCP completion). Set the status using - // the Intent's detailed state. - ap.setStatus(detailedState); - ap.unblockRefresh(); - } - } - - //============================ - // Wifi callbacks - //============================ - - private void handleNetworkStateChanged(NetworkInfo info, String bssid) { - final AccessPointState ap = getCurrentAp(); - NetworkInfo.DetailedState detailedState = info.getDetailedState(); - - if (LOGV) { - Log.v(TAG, "State change received " + info.toString() + ", or " - + detailedState + " on " + bssid + " matched to " + ap); - } - - handleDisablingScanWhileObtainingAddress(detailedState); - - // This will update the AP with its new info - refreshStatus(ap, detailedState); - - boolean isDisconnected = info.getState().equals(State.DISCONNECTED); - if (ap != null && info.isConnectedOrConnecting()) { - setPrimaryAp(ap); - - if (LOGV) { - Log.v(TAG, " Updated " + ap + " to be primary"); - } - - } else if (isDisconnected) { - - /* - * When we drop off a network (for example, the router is powered - * down when we were connected), we received a DISCONNECT event - * without a BSSID. We should not have a primary AP anymore. - */ - setPrimaryAp(null); - - if (LOGV) { - Log.v(TAG, " Cleared primary"); - } - - } else if (detailedState.equals(DetailedState.FAILED)) { - - /* - * Doh, failed for whatever reason. Unset the primary AP, but set - * failed status on the AP that failed. - */ - setPrimaryAp(null); - ap.setStatus(DetailedState.FAILED); - - // Bring up error dialog - error(R.string.wifi_generic_connection_error); - - } else if (LOGV) { - Log.v(TAG, " Did not update any AP to primary, could have updated " - + ap + " but we aren't connected or connecting"); - } - - if ((ap != null) && (info.isConnected() - || (detailedState == DetailedState.OBTAINING_IPADDR))) { - /* - * Sometimes the scan results do not contain the AP even though it's - * clearly connected. This may be because we do passive background - * scanning that isn't as 'strong' as active scanning, so even - * though a network is nearby, it won't be seen by the passive - * scanning. If we are connected (or obtaining IP) then we know it - * is seen. - */ - ap.setSeen(true); - } - - attemptReenableAllAps(); - } - - private void handleDisablingScanWhileObtainingAddress(DetailedState detailedState) { - - if (detailedState == DetailedState.OBTAINING_IPADDR) { - mIsObtainingAddress = true; - - // We will not scan while obtaining an IP address - removeFutureScans(); - - } else { - mIsObtainingAddress = false; - - // Start continuous scan - queueContinuousScan(); - } - } - - private void handleScanResultsAvailable() { - synchronized(this) { - // In the end, we'll moved the ones no longer seen into the mApOtherList - List<AccessPointState> oldScanList = mApScanList; - List<AccessPointState> newScanList = - new ArrayList<AccessPointState>(oldScanList.size()); - - List<ScanResult> list = mWifiManager.getScanResults(); - if (list != null) { - for (int i = list.size() - 1; i >= 0; i--) { - final ScanResult scanResult = list.get(i); - - if (LOGV) { -// Log.v(TAG, " " + scanResult); - } - - if (scanResult == null) { - continue; - } - - /* - * Ignore adhoc, enterprise-secured, or hidden networks. - * Hidden networks show up with empty SSID. - */ - if (AccessPointState.isAdhoc(scanResult) - || AccessPointState.isEnterprise(scanResult) - || TextUtils.isEmpty(scanResult.SSID)) { - continue; - } - - final String ssid = AccessPointState.convertToQuotedString(scanResult.SSID); - String security = AccessPointState.getScanResultSecurity(scanResult); - - // See if this AP is part of a group of APs (e.g., any large - // wifi network has many APs, we'll only show one) that we've - // seen in this scan - AccessPointState ap = findApLocked(newScanList, AccessPointState.NETWORK_ID_ANY, - AccessPointState.BSSID_ANY, ssid, security); - - // Yup, we've seen this network. - if (ap != null) { - // Use the better signal - if (WifiManager.compareSignalLevel(scanResult.level, ap.signal) > 0) { - ap.setSignal(scanResult.level); - } - - if (LOGV) { -// Log.v(TAG, " Already seen, continuing.."); - } - - continue; - } - - // Find the AP in either our old scan list, or our non-seen - // configured networks list - ap = findApLocked(AccessPointState.NETWORK_ID_ANY, AccessPointState.BSSID_ANY, - ssid, security); - - if (ap != null) { - // Remove the AP from both (no harm if one doesn't contain it) - oldScanList.remove(ap); - mApOtherList.remove(ap); - } else { - ap = new AccessPointState(mContext); -// if (LOGV) Log.v(TAG, "Created " + ap); - } - - // Give it the latest state - ap.updateFromScanResult(scanResult); - - if (mCallback != null) { - mCallback.onAccessPointSetChanged(ap, true); - } - - newScanList.add(ap); - } - } - - // oldScanList contains the ones no longer seen - List<AccessPointState> otherList = mApOtherList; - for (int i = oldScanList.size() - 1; i >= 0; i--) { - final AccessPointState ap = oldScanList.get(i); - - if (ap.configured) { - - // Keep it around, since it is configured - ap.setSeen(false); - otherList.add(ap); - - } else { - - // Remove it since it is not configured and not seen - removeApFromUi(ap); - } - } - - mApScanList = newScanList; - } - - onScanningEnded(); - } - - private void handleSupplicantConnectionChanged(boolean connected) { - if (mCallback != null) { - mCallback.onAccessPointsStateChanged(connected); - } - - if (connected) { - refreshAll(true); - } - } - - private void handleWifiStateChanged(int wifiState) { - - if (wifiState == WIFI_STATE_ENABLED) { - loadConfiguredAccessPoints(); - attemptScan(); - - } else if (wifiState == WIFI_STATE_DISABLED) { - removeFutureScans(); - if (LOGV) Log.v(TAG, "Clearing AP lists because wifi is disabled"); - clearApLists(); - } - - if (mCallback != null) { - mCallback.onAccessPointsStateChanged(wifiState == WIFI_STATE_ENABLED); - } - } - - private void handleSignalChanged(int rssi) { - - if (mCurrentPrimaryAp != null) { - mCurrentPrimaryAp.setSignal(rssi); - } - } - - private void handleSupplicantStateChanged(SupplicantState state, boolean hasError, int error) { - mCurrentSupplicantState = state; - - if (SupplicantState.FOUR_WAY_HANDSHAKE.equals(state)) { - mLastAuthenticatingAp = getCurrentAp(); - } - - if (hasError) { - handleSupplicantStateError(error); - } - } - - private void handleSupplicantStateError(int supplicantError) { - if (supplicantError == WifiManager.ERROR_AUTHENTICATING) { - if (mCallback != null) { - if (mLastAuthenticatingAp != null) { - mCallback.onRetryPassword(mLastAuthenticatingAp); - } - } - } - } - - private void handleNetworkIdsChanged() { - synchronized (this) { - final List<WifiConfiguration> configs = getConfiguredNetworks(); - - for (int i = configs.size() - 1; i >= 0; i--) { - final WifiConfiguration config = configs.get(i); - - AccessPointState ap; - // Since network IDs have changed, we can't use it to find our previous AP state - ap = findApLocked(AccessPointState.NETWORK_ID_ANY, config.BSSID, config.SSID, - AccessPointState.getWifiConfigurationSecurity(config)); - - if (ap == null) { - continue; - } - - ap.setNetworkId(config.networkId); - } - } - } - - private class MyHandler extends Handler { - - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case MESSAGE_ATTEMPT_SCAN: - attemptScan(); - break; - } - } - } - -} diff --git a/src/com/android/settings/wifi/WifiSettings.java b/src/com/android/settings/wifi/WifiSettings.java deleted file mode 100644 index d2683c0..0000000 --- a/src/com/android/settings/wifi/WifiSettings.java +++ /dev/null @@ -1,438 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.settings.wifi; - -import com.android.settings.ProgressCategory; -import com.android.settings.R; - -import android.app.Dialog; -import android.content.DialogInterface; -import android.content.Intent; -import android.net.wifi.WifiManager; -import android.os.Bundle; -import android.preference.Preference; -import android.preference.PreferenceActivity; -import android.preference.PreferenceScreen; -import android.preference.CheckBoxPreference; -import android.provider.Settings; -import android.util.Log; -import android.view.ContextMenu; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.view.ContextMenu.ContextMenuInfo; -import android.widget.AdapterView; -import android.widget.Toast; -import android.widget.AdapterView.AdapterContextMenuInfo; - -import java.util.Set; -import java.util.WeakHashMap; - -/** - * Settings screen for WiFi. This will be launched from the main system settings. - */ -public class WifiSettings extends PreferenceActivity implements WifiLayer.Callback, - DialogInterface.OnDismissListener { - - private static final String TAG = "WifiSettings"; - - //============================ - // Preference/activity member variables - //============================ - - private static final String INSTANCE_KEY_DIALOG_BUNDLE = - "com.android.settings.wifi.WifiSettings:dialogBundle"; - /* - * We don't use Activity's dialog management because AlertDialog isn't fully - * able to change many of its features after it's been created, and the - * dialog management only creates once. - */ - private Dialog mDialog; - - private static final String KEY_ADD_OTHER_NETWORK = "add_other_network"; - - private static final int CONTEXT_MENU_ID_CONNECT = Menu.FIRST; - private static final int CONTEXT_MENU_ID_FORGET = Menu.FIRST + 1; - private static final int CONTEXT_MENU_ID_CHANGE_PASSWORD = Menu.FIRST + 2; - - private static final int MENU_ID_SCAN = Menu.FIRST; - private static final int MENU_ID_ADVANCED = Menu.FIRST + 1; - - private static final String KEY_WIFI_ENABLED = "wifi_enabled"; - private static final String KEY_OPEN_NETWORK_NOTIFICATIONS_ENABLED = - "open_network_notifications_enabled"; - private static final String KEY_ACCESS_POINTS = "access_points"; - - private ProgressCategory mApCategory; - private CheckBoxPreference mWifiEnabled; - private WifiEnabler mWifiEnabler; - private CheckBoxPreference mOpenNetworkNotificationsEnabled; - private Preference mAddOtherNetwork; - - private WeakHashMap<AccessPointState, AccessPointPreference> mAps; - - //============================ - // Wifi member variables - //============================ - - private WifiLayer mWifiLayer; - - //============================ - // Activity lifecycle - //============================ - - public WifiSettings() { - mAps = new WeakHashMap<AccessPointState, AccessPointPreference>(); - mWifiLayer = new WifiLayer(this, this); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - onCreatePreferences(); - mWifiLayer.onCreate(); - - onCreatedWifi(); - mWifiLayer.onCreatedCallback(); - } - - /** - * Shouldn't have any dependency on the wifi layer. - */ - private void onCreatePreferences() { - addPreferencesFromResource(R.xml.wifi_settings); - - final PreferenceScreen preferenceScreen = getPreferenceScreen(); - - mApCategory = (ProgressCategory) preferenceScreen.findPreference(KEY_ACCESS_POINTS); - // We don't want the ordering to be the order preferences are added, - // instead we want*: - // 1) preferred, visible APs - // 2) visible APs - // 3) preferred, APs out of range - // * this ordering logic is in AccessPointPreference's compareTo - mApCategory.setOrderingAsAdded(false); - - mWifiEnabled = (CheckBoxPreference) preferenceScreen.findPreference(KEY_WIFI_ENABLED); - mWifiEnabler = new WifiEnabler(this, (WifiManager) getSystemService(WIFI_SERVICE), - mWifiEnabled); - - mOpenNetworkNotificationsEnabled = (CheckBoxPreference) preferenceScreen - .findPreference(KEY_OPEN_NETWORK_NOTIFICATIONS_ENABLED); - mOpenNetworkNotificationsEnabled.setChecked(Settings.Secure.getInt(getContentResolver(), - Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1); - - mAddOtherNetwork = preferenceScreen.findPreference(KEY_ADD_OTHER_NETWORK); - - registerForContextMenu(getListView()); - } - - private void onCreatedWifi() { - } - - @Override - protected void onResume() { - super.onResume(); - mWifiLayer.onResume(); - mWifiEnabler.resume(); - } - - @Override - protected void onPause() { - super.onPause(); - mWifiLayer.onPause(); - mWifiEnabler.pause(); - } - - @Override - protected void onDestroy() { - super.onDestroy(); - - if (mDialog != null) { - mDialog.dismiss(); - } - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - super.onCreateOptionsMenu(menu); - - menu.add(0, MENU_ID_SCAN, 0, R.string.scan_wifi) - .setIcon(R.drawable.ic_menu_scan_network); - - menu.add(0, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced) - .setIcon(android.R.drawable.ic_menu_manage); - - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - super.onOptionsItemSelected(item); - - switch (item.getItemId()) { - - case MENU_ID_SCAN: - mWifiLayer.attemptScan(); - return true; - - case MENU_ID_ADVANCED: - Intent intent = new Intent(this, AdvancedSettings.class); - startActivity(intent); - return true; - - default: - return false; - } - } - - @Override - protected void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - - if (mDialog != null) { - Bundle dialogBundle = mDialog.onSaveInstanceState(); - outState.putBundle(INSTANCE_KEY_DIALOG_BUNDLE, dialogBundle); - } - } - - @Override - protected void onRestoreInstanceState(Bundle state) { - super.onRestoreInstanceState(state); - - Bundle dialogBundle = state.getBundle(INSTANCE_KEY_DIALOG_BUNDLE); - if (dialogBundle != null) { - mDialog = new AccessPointDialog(this, mWifiLayer); - mDialog.onRestoreInstanceState(dialogBundle); - showDialog(mDialog); - } - } - - /** - * {@inheritDoc} - */ - public void onDismiss(DialogInterface dialog) { - if (dialog == mDialog) { - mDialog = null; - } - } - - @Override - public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { - super.onCreateContextMenu(menu, v, menuInfo); - - AccessPointState state = getStateFromMenuInfo(menuInfo); - if (state == null) { - return; - } - - menu.setHeaderTitle(state.getHumanReadableSsid()); - - if (state.isConnectable()) { - menu.add(0, CONTEXT_MENU_ID_CONNECT, 0, R.string.wifi_context_menu_connect); - } - - if (state.isForgetable()) { - menu.add(0, CONTEXT_MENU_ID_FORGET, 1, R.string.wifi_context_menu_forget); - - if (state.hasPassword()) { - menu.add(0, CONTEXT_MENU_ID_CHANGE_PASSWORD, 2, - R.string.wifi_context_menu_change_password); - } - } - } - - @Override - public boolean onContextItemSelected(MenuItem item) { - - AccessPointState state = getStateFromMenuInfo(item.getMenuInfo()); - if (state == null) { - return false; - } - - switch (item.getItemId()) { - - case CONTEXT_MENU_ID_CONNECT: - connectToNetwork(state); - return true; - - case CONTEXT_MENU_ID_FORGET: - mWifiLayer.forgetNetwork(state); - return true; - - case CONTEXT_MENU_ID_CHANGE_PASSWORD: - showAccessPointDialog(state, AccessPointDialog.MODE_CONFIGURE); - return true; - - default: - return false; - } - } - - /** - * Decides what needs to happen to connect to a particular access point. If - * it is secured and doesn't already have a password, it will bring up a - * password box. Otherwise it will just connect. - */ - private void connectToNetwork(AccessPointState state) { - if (state.hasSecurity() && !state.hasPassword()) { - showAccessPointDialog(state, AccessPointDialog.MODE_INFO); - } else { - mWifiLayer.connectToNetwork(state); - } - } - - private AccessPointState getStateFromMenuInfo(ContextMenuInfo menuInfo) { - if ((menuInfo == null) || !(menuInfo instanceof AdapterContextMenuInfo)) { - return null; - } - - AdapterContextMenuInfo adapterMenuInfo = (AdapterContextMenuInfo) menuInfo; - Preference pref = (Preference) getPreferenceScreen().getRootAdapter().getItem( - adapterMenuInfo.position); - if (pref == null || !(pref instanceof AccessPointPreference)) { - return null; - } - - return ((AccessPointPreference) pref).getAccessPointState(); - } - - //============================ - // Preference callbacks - //============================ - - @Override - public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { - super.onPreferenceTreeClick(preferenceScreen, preference); - - if (preference == mAddOtherNetwork) { - showAddOtherNetworkDialog(); - } else if (preference == mOpenNetworkNotificationsEnabled) { - Settings.Secure.putInt(getContentResolver(), - Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, - mOpenNetworkNotificationsEnabled.isChecked() ? 1 : 0); - } else if (preference instanceof AccessPointPreference) { - AccessPointState state = ((AccessPointPreference) preference).getAccessPointState(); - showAccessPointDialog(state, AccessPointDialog.MODE_INFO); - } - - return false; - } - - //============================ - // Wifi-related - //============================ - - public WifiLayer getWifiLayer() { - return mWifiLayer; - } - - private void showAddOtherNetworkDialog() { - AccessPointDialog dialog = new AccessPointDialog(this, mWifiLayer); - dialog.setState(new AccessPointState(this)); - dialog.setMode(AccessPointDialog.MODE_CONFIGURE); - dialog.setTitle(R.string.wifi_add_other_network); - dialog.setAutoSecurityAllowed(false); - showDialog(dialog); - } - - public void showAccessPointDialog(AccessPointState state, int mode) { - AccessPointDialog dialog = new AccessPointDialog(this, mWifiLayer); - dialog.setMode(mode); - dialog.setState(state); - showDialog(dialog); - } - - private void showDialog(Dialog dialog) { - // Have only one dialog open at a time - if (mDialog != null) { - mDialog.dismiss(); - } - - mDialog = dialog; - dialog.setOnDismissListener(this); - if (dialog != null) { - dialog.show(); - } - } - - //============================ - // Wifi callbacks - //============================ - - public void onError(int messageResId) { - Toast.makeText(this, messageResId, Toast.LENGTH_LONG).show(); - } - - public void onScanningStatusChanged(boolean started) { - mApCategory.setProgress(started); - } - - public void onAccessPointSetChanged(AccessPointState ap, boolean added) { - - AccessPointPreference pref = mAps.get(ap); - - if (WifiLayer.LOGV) { - Log.v(TAG, "onAccessPointSetChanged with " + ap + " and " - + (added ? "added" : "removed") + ", found pref " + pref); - } - - if (added) { - - if (pref == null) { - pref = new AccessPointPreference(this, ap); - mAps.put(ap, pref); - } else { - pref.setEnabled(true); - } - - mApCategory.addPreference(pref); - - } else { - - mAps.remove(ap); - - if (pref != null) { - mApCategory.removePreference(pref); - } - - } - } - - public void onAccessPointsStateChanged(boolean enabled) { - if (enabled) { - mApCategory.setEnabled(true); - } else { - mApCategory.removeAll(); - mAps.clear(); - } - - mAddOtherNetwork.setEnabled(enabled); - } - - public void onRetryPassword(AccessPointState ap) { - - if ((mDialog != null) && mDialog.isShowing()) { - // If we're already showing a dialog, ignore this request - return; - } - - showAccessPointDialog(ap, AccessPointDialog.MODE_RETRY_PASSWORD); - } - -} diff --git a/src/com/android/settings/wifi/WifiStatus.java b/src/com/android/settings/wifi/WifiStatus.java deleted file mode 100644 index d4b6431..0000000 --- a/src/com/android/settings/wifi/WifiStatus.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.settings.wifi; - -import com.android.settings.R; - -import android.content.Context; -import android.net.NetworkInfo; -import android.net.wifi.WifiInfo; -import android.text.TextUtils; - -public class WifiStatus { - - // e.g., "Connecting" - public static String sScanning; - public static String sConnecting; - public static String sAuthenticating; - public static String sObtainingIp; - public static String sConnected; - public static String sDisconnecting; - public static String sDisconnected; - public static String sFailed; - - // e.g., "Connecting to %1$s" - public static String sScanningFragment; - public static String sConnectingFragment; - public static String sAuthenticatingFragment; - public static String sObtainingIpFragment; - public static String sConnectedFragment; - public static String sDisconnectingFragment; - public static String sDisconnectedFragment; - public static String sFailedFragment; - - private static void fillStrings(Context context) { - sScanning = context.getString(R.string.status_scanning); - sConnecting = context.getString(R.string.status_connecting); - sAuthenticating = context.getString(R.string.status_authenticating); - sObtainingIp = context.getString(R.string.status_obtaining_ip); - sConnected = context.getString(R.string.status_connected); - sDisconnecting = context.getString(R.string.status_disconnecting); - sDisconnected = context.getString(R.string.status_disconnected); - sFailed = context.getString(R.string.status_failed); - - sScanningFragment = context.getString(R.string.fragment_status_scanning); - sConnectingFragment = context.getString(R.string.fragment_status_connecting); - sAuthenticatingFragment = context.getString(R.string.fragment_status_authenticating); - sObtainingIpFragment = context.getString(R.string.fragment_status_obtaining_ip); - sConnectedFragment = context.getString(R.string.fragment_status_connected); - sDisconnectingFragment = context.getString(R.string.fragment_status_disconnecting); - sDisconnectedFragment = context.getString(R.string.fragment_status_disconnected); - sFailedFragment = context.getString(R.string.fragment_status_failed); - } - - public static String getStatus(Context context, String ssid, - NetworkInfo.DetailedState detailedState) { - - if (!TextUtils.isEmpty(ssid) && isLiveConnection(detailedState)) { - return getPrintableFragment(context, detailedState, ssid); - } else { - return getPrintable(context, detailedState); - } - } - - public static boolean isLiveConnection(NetworkInfo.DetailedState detailedState) { - return detailedState != NetworkInfo.DetailedState.DISCONNECTED - && detailedState != NetworkInfo.DetailedState.FAILED - && detailedState != NetworkInfo.DetailedState.IDLE - && detailedState != NetworkInfo.DetailedState.SCANNING; - } - - public static String getPrintable(Context context, - NetworkInfo.DetailedState detailedState) { - - if (sScanning == null) { - fillStrings(context); - } - - switch (detailedState) { - case AUTHENTICATING: - return sAuthenticating; - case CONNECTED: - return sConnected; - case CONNECTING: - return sConnecting; - case DISCONNECTED: - return sDisconnected; - case DISCONNECTING: - return sDisconnecting; - case FAILED: - return sFailed; - case OBTAINING_IPADDR: - return sObtainingIp; - case SCANNING: - return sScanning; - default: - return null; - } - } - - public static String getPrintableFragment(Context context, - NetworkInfo.DetailedState detailedState, String apName) { - - if (sScanningFragment == null) { - fillStrings(context); - } - - String fragment = null; - switch (detailedState) { - case AUTHENTICATING: - fragment = sAuthenticatingFragment; - break; - case CONNECTED: - fragment = sConnectedFragment; - break; - case CONNECTING: - fragment = sConnectingFragment; - break; - case DISCONNECTED: - fragment = sDisconnectedFragment; - break; - case DISCONNECTING: - fragment = sDisconnectingFragment; - break; - case FAILED: - fragment = sFailedFragment; - break; - case OBTAINING_IPADDR: - fragment = sObtainingIpFragment; - break; - case SCANNING: - fragment = sScanningFragment; - break; - } - - return String.format(fragment, apName); - } - -} |