在Android中监视wifi状态

. Confirm if Wifi is On
Using isEnabled() in WifiManager.
If not, use setEnabled(true) to turn on it.
Note:
May take some time, suggest to wait 1~3 seconds.

2. Scan AP
Using scanAP() in WifiManager
The result will not reply immediately,
so we set a receiver to receive the result latter.
The receiver should extend from BroadcastReceiver to receive the broadcast message.
Ex:
if( wifiManager.startScan()){
IntentFilter inf = new IntentFilter();
inf.addAction(WifiManager.SCAN_RESULT_AVAILABLE_ACTION);
registerReceiver(new WifiResultManager(), inf);
}

class WifiResultManager extends BroadcastReceiver{
public WifiResultManager(){
}

public void onReceive(Context cxt, Intent it){
//Do something
}
}


3. Connect to AP
Using WifiConfiguration to set the specified settings.
(1) If a password is needed, you should set to string wepKeys[i] (i=1~3).
If the password only contains 0-9A-Fa-f (Hex), you can just put the password to the string,
but if it have ascii codes, you should add additional /" to both side of the string.
(Ex: if password="wifimanager00", you should save as "/"wifimanager00/"")

(2) Set the BSSID but SSID.
Note:
I don't know why it's not work after I set the SSID.

(3) Choose the correct settings.
For example, you can set it for open network.
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.status=WifiConfiguration.Status.ENABLED;

then add it to manager and enable it.
conf.networkId = manager.addNetwork(conf);
//At this part, you can check the existing network to update it by using updateNetwork();
//Simplely, just add a new one.
manager.enableNetwork(conf.networkId, true);

After you done these works,
you will find that, yes, the connection is established, but no ip address.
This is because it will take some time to get the IP Address from AP.
You can add another receiver to listen the NETWORK_STATE_CHANGED_ACTION message.
In general, it may take 3~10 seconds to get the correct IP Address.

Now, you can use it. Have fun to your Java.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值