最近有需求做一个wifi列表 这里总结下留个笔记
主要用到WifiManager,ScanResult,WifiConfiguration,WifiInfo这四个类
WifiManager
1、获取WifiManager对象
mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
打开wifi
mWifiManager.setWifiEnabled(true);
关闭wifi
mWifiManager.setWifiEnabled(false);
判断wifi是否开启
mWifiManager.isWifiEnabled();
在打开和关闭wifi时监听wifi状态
注册广播接受者来监听wifi状态 后面给出整个接收者
WifiManager.WIFI_STATE_CHANGED_ACTION
WIFI状态int值对应的状态:
WifiManager.WIFI_STATE_DISABLED ==1 WIFI网卡不可用
WifiManager.WIFI_STATE_DISABLING ==0 WIFI正在关闭
WifiManager.WIFI_STATE_ENABLED==3 WIFI网卡可用
WifiManager.WIFI_STATE_ENABLING==2 WIFI网卡正在打开
WifiManager.WIFI_STATE_UNKNOWN==4 未知网卡状态
扫描热点
mWifiManager.startScan();//返回true开始扫描
扫描完成后系统会通过广播形式通知用户
用户通过注册下面action的广播
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION
ScanResult
通过下面方式拿到扫描到的热点
List<ScanResult> scanResults = mWifiManager.getScanResults();
下面通过ScanResult来拿到热点的信息
ScanResult类的成员变量:
String SSID:网络名称。
WifiSsid wifiSsid:Ascii编码的SSID。
String BSSID:AP的地址。
String capabilities:描述认证、密钥管理以及加密方式,通过AP来支持。
int level:发现的信号等级,单位是dBm,也被称作RSSI,通过调用WifiManager的caculateSignalLevel方法将该数值进行换算,换算成一个绝对信号等级呈现给用户。
int frequency:channel(客户端与AP通信的信道)的频率,单位MHz。
long timestamp:从启动开始到该扫描记录最后一次被发现经过的微秒数。
long seen:代表该扫描结果最后一次被发现的日期,从1970年到该日期的毫秒数。
int isAutoJoinCandidate:代表该扫描结果是否是一个有效的自动加入的候选项。
int autoJoinStatus:表示join的状态。
numIpConfigFailure:IP配置失败的次数。
long blackListTimestamp:我们最后一次将该ScanResult加入黑名单的时间。
boolean untrusted:如果为true,说明该扫描结果并不是用户已保存配置中的部分。
int numConnection:我们连接到该扫描结果的次数。
int numUsage:自动加入使用该扫描结果的次数。
int distanceCm:到AP的大概距离,单位:米,如果无法获取该值,则该值为UNSPECIFIED。
int distanceSdCm:到AP距离的标准差,若无法获取该值,则该值为UNSPECIFIED。
public InformationElement informationElements[]:在信号中发现的信息元素。
WifiConfiguration
获到热点configuration
保存每个热点的配置信息
List<WifiConfiguration> configs = mWifiManager
.getConfiguredNetworks();
//已经保存热点信息 直接连接
mWifiManager.connect(configs.get(i), mConnectListener);
//取消保存
mWifiManager.removeNetwork(networkId);
连接热点
mWifiManager.connect(config, mConnectListener);
参数1:热点配置信息
参数2:连接监听
新建WifiConfiguration连接AP
//这个是我对话框的文本输入
EditText mPasswordView = mDialog.getEditText();
mConfig = new WifiConfiguration();
mConfig.SSID = "\"" + mAp.ssid + "\"";//配置热点的ssid
if (mPasswordView.length() != 0) {
String password = mPasswordView.getText().toString();
//配置密码
if (password.matches("[0-9A-Fa-f]{64}")) {
mConfig.preSharedKey = password;
} else {
mConfig.preSharedKey = '"' + password + '"';
}
}
mWifiManager.connect(mConfig, mConnectListener);
//连接监听
private final ActionListener mConnectListener = new ActionListener() {
@Override
public void onSuccess() {
if (DEBUG)
Log.d(TAG, "connect success");
}
@Override
public void onFailure(int reason) {
if (DEBUG)
Log.d(TAG, "connect failure reason=" + reason);
}
};
监听热点连接状态
通过监听下面广播来监听
正在扫描...
正在连接...
正在进行身份验证...
正在获取IP地址...
等状态
WifiManager.NETWORK_STATE_CHANGED_ACTION
广播接收者
private final class Receiver extends BroadcastReceiver {
private boolean mRegistered;
public void setListening(boolean listening) {
if (listening && !mRegistered) {
if (DEBUG)
Log.d(TAG, "Registering receiver");
final IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
filter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
filter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.RSSI_CHANGED_ACTION);
mContext.registerReceiver(this, filter);
mRegistered = true;
} else if (!listening && mRegistered) {
if (DEBUG)
Log.d(TAG, "Unregistering receiver");
mContext.unregisterReceiver(this);
mRegistered = false;
}
}
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG)
Log.d(TAG, "onReceive " + intent.getAction());
if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent
.getAction())) {
updateAccessPoints("", "");
mScanning = false;
} else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent
.getAction())) {
NetworkInfo networkInfo = (NetworkInfo) intent
.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (mWifiManager.isWifiEnabled()) {
WifiInfo info = mWifiManager.getConnectionInfo();
String summary = Summary
.get(mContext,
info.getSSID(),
networkInfo.getDetailedState(),
info.getNetworkId() == WifiConfiguration.INVALID_NETWORK_ID);
updateAccessPoints(info.getSSID(), summary);
//Log.v("lmjssjj",
// "summary:" + summary + "===" + info.getSSID());
}
//判断wifi状态 根据不同的状态返回不同的字符串
class Summary {
static String get(Context context, String ssid, DetailedState state, boolean isEphemeral) {
if (state == DetailedState.CONNECTED && isEphemeral && ssid == null) {
// Special case for connected + ephemeral networks.
return context.getString(R.string.connected_via_wfa);
}
String[] formats = context.getResources().getStringArray((ssid == null)
? R.array.wifi_status : R.array.wifi_status/*R.array.wifi_status_with_ssid*/);
int index = state.ordinal();
if (index >= formats.length || formats[index].length() == 0) {
return null;
}
return String.format(formats[index], ssid);
}
static String get(Context context, DetailedState state, boolean isEphemeral) {
return get(context, null, state, isEphemeral);
}
}
<string-array name="wifi_status">
<!-- Status message of Wi-Fi when it is idle. -->
<item></item>
<!-- Status message of Wi-Fi when it is scanning. -->
<item>Scanning\u2026</item>
<!-- Status message of Wi-Fi when it is connecting. -->
<item>Connecting\u2026</item>
<!-- Status message of Wi-Fi when it is authenticating. -->
<item>Authenticating\u2026</item>
<!-- Status message of Wi-Fi when it is obtaining IP address. -->
<item>Obtaining IP address\u2026</item>
<!-- Status message of Wi-Fi when it is connected. -->
<item>Connected</item>
<!-- Status message of Wi-Fi when it is suspended. -->
<item>Suspended</item>
<!-- Status message of Wi-Fi when it is disconnecting. -->
<item>Disconnecting\u2026</item>
<!-- Status message of Wi-Fi when it is disconnected. -->
<item>Disconnected</item>
<!-- Status message of Wi-Fi when it is a failure. -->
<item>Unsuccessful</item>
<!-- Status message of Wi-Fi when it is blocked. -->
<item>Blocked</item>
<!-- Status message of Wi-Fi when connectiong is being verified. -->
<item>Temporarily avoiding poor connection</item>
</string-array>