主类:
- public class WifiAdmin {
- // 定义WifiManager对象
- private WifiManager mWifiManager;
- // 定义WifiInfo对象
- private WifiInfo mWifiInfo;
- // 扫描出的网络连接列表,ScanResult主要用来描述已经检测出的接入点,包括介入点的地址,介入点的名称,身份认证,频率,信号强度等信息
- private List<ScanResult> mWifiList;
- // 网络连接列表
- private List<WifiConfiguration> mWifiConfiguration;
- // 定义一个WifiLock
- WifiLock mWifiLock;
- // 构造器
- public WifiAdmin(Context context) {
- // 取得WifiManager对象
- mWifiManager = (WifiManager) context
- .getSystemService(Context.WIFI_SERVICE);
- // 取得WifiInfo对象
- mWifiInfo = mWifiManager.getConnectionInfo();
- }
- // 打开WIFI
- public void openWifi() {
- if (!mWifiManager.isWifiEnabled()) {
- mWifiManager.setWifiEnabled(true);
- System.out.println("wifi打开成功!");
- }
- // if (mWifiManager.disconnect()) {
- // mWifiManager.setWifiEnabled(true);
- // System.out.println("wifi打开成功!!");
- // }
- }
- // 关闭WIFI
- public void closeWifi() {
- if (mWifiManager.isWifiEnabled()) {
- mWifiManager.setWifiEnabled(false);
- }
- }
- // 检查当前WIFI状态
- public int checkState() {
- return mWifiManager.getWifiState();
- }
- // 锁定WifiLock
- public void acquireWifiLock() {
- mWifiLock.acquire();
- }
- // 解锁WifiLock
- public void releaseWifiLock() {
- // 判断时候锁定
- if (mWifiLock.isHeld()) {
- mWifiLock.acquire();
- }
- }
- // 创建一个WifiLock
- public void creatWifiLock() {
- mWifiLock = mWifiManager.createWifiLock("Test");
- }
- // 得到配置好的网络
- public List<WifiConfiguration> getConfiguration() {
- return mWifiConfiguration;
- }
- // 指定配置好的网络进行连接
- public void connectConfiguration(int index) {
- // 索引大于配置好的网络索引返回
- if (index > mWifiConfiguration.size()) {
- System.out.println("连接失败!");
- return;
- }
- // 连接配置好的指定ID的网络
- mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,
- true);
- System.out.println(index + "连接成功!");
- }
- public void startScan() {
- mWifiManager.startScan();
- // 得到扫描结果
- mWifiList = mWifiManager.getScanResults();
- // 得到配置好的网络连接
- mWifiConfiguration = mWifiManager.getConfiguredNetworks();
- }
- // 得到网络列表
- public List<ScanResult> getWifiList() {
测试:
- public class TestActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // 测试activity
- super.onCreate(savedInstanceState);
- // setContentView(R.layout.show_value);
- WifiAdmin wifiAdmin = new WifiAdmin(TestActivity.this);
- wifiAdmin.openWifi();
- <span style="white-space:pre"> </span>//需要连接的网络信息,类型1表示密码为空
- WifiConfiguration wcg=wifiAdmin.CreateWifiInfo("wifi name", "", 1);
- <span style="white-space:pre"> </span>//加入配置的网络
- wifiAdmin.addNetwork(wcg);
- }
- }
【原文:http://blog.csdn.net/yhm2046/article/details/8540191】