auto import from //depot/cupcake/@135843

This commit is contained in:
The Android Open Source Project
2009-03-03 18:28:52 -08:00
parent a578a6c4ad
commit 4e14e5ccbf
241 changed files with 0 additions and 36078 deletions

View File

@@ -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());
}
}
}

View File

@@ -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);
}
}

View File

@@ -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];
}
};
}

View File

@@ -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));
}
}

View File

@@ -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!";
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -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);
}
}

View File

@@ -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);
}
}