Android Wifi和蓝牙操作(一)

简介: Android Wifi和蓝牙操作(一)

/** 本文中代码仅供参考, 无法直接运行 **/


权限申明:


<!-- 访问网络权限 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission>    
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>       
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> 
  <uses-permission android:name="android.permission.INTERNET"></uses-permission> 
  <uses-permission android:name="android.permission.BLUETOOTH"></uses-permission> 
  <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission> 
  <uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>  
  <!-- after 6.0 for BT -->
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

1. 扫描WIFI热点


调用WifiManager.startScan()


final int MSG_SCAN_START = 0x01;
  //final int MSG_SCAN_COMPLETE = 0x02;
  private Handler mHandler = new Handler() {
  public void handleMessage(Message msg) {
    if (MSG_SCAN_START == msg.what) {
    if(debugScan)ALog.d(TAG, "start scan wifi access point");
    mWifiManager.startScan();//启动扫描
          //we should start scan again to refresh wifi list state after every 10 sec
          mHandler.sendEmptyMessageDelayed(MSG_SCAN_START, 10 * 1000);
    }
/*    if (MSG_SCAN_COMPLETE == msg.what) {
    onWifiScanSuccess();
    }*/
  };
  };

监听WIFI状态变化


IntentFilter filter = new IntentFilter();
//WIFI 开关   
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
//网络连接状态,  
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
//扫描结果   
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
   wifiReceiver = new WifiChangedReceiver();
   registerReceiver(wifiReceiver, filter);

扫描完成后,通过获取ScanResult来显示列表,  

//ScanResult 中, 包含了SSID, BSSID, 加密码类型等信息.
mWifiManager.getScanResults();

要完整的状态还需要配合 WifiConfiguration一起:

//如验证失败原因
               switch (mConfig.disableReason) {
                    case WifiConfiguration.DISABLED_AUTH_FAILURE:
                        summary.append(context.getString(R.string.wifi_disabled_password_failure));
                        break;
                    case WifiConfiguration.DISABLED_DHCP_FAILURE:
                    case WifiConfiguration.DISABLED_DNS_FAILURE:
                        summary.append(context.getString(R.string.wifi_disabled_network_failure));
                        break;
                    case WifiConfiguration.DISABLED_UNKNOWN_REASON:
                    case WifiConfiguration.DISABLED_ASSOCIATION_REJECT:
                        summary.append(context.getString(R.string.wifi_disabled_generic));
                        break;


2.  WIFI开关


//开关的代码比较简单:
WifiManager.setWifiEnabled(boolean open)


状态监听:


if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {// 这个监听wifi的打开与关闭,与wifi的连接无关
             int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
             Log.i(TAG, "wifiState" + wifiState);
             switch (wifiState) {
              case WifiManager.WIFI_STATE_DISABLED:
                  break;
              case WifiManager.WIFI_STATE_DISABLING:
                  break;
              case WifiManager.WIFI_STATE_ENABLED:{
                Log.i(TAG, "WIFI_STATE_ENABLED");
                mHandler.sendEmptyMessageDelayed(MSG_SCAN_START, 1000);
                break;
              }
             //
             }


3. WIFI热点连接


/*** 
  * 配置要连接的WIFI热点信息     
  * @param SSID 
  * @param password 
  * @param type  加密类型 
  * @return 
  */       
  public WifiConfiguration createWifiInfo(String SSID, String password, int type) {    
  Log.e(TAG, "SSID = " + SSID + "## Password = " + password + "## Type = " + type);    
  WifiConfiguration config = new WifiConfiguration();    
  config.allowedAuthAlgorithms.clear();    
  config.allowedGroupCiphers.clear();    
  config.allowedKeyManagement.clear();    
  config.allowedPairwiseCiphers.clear();    
  config.allowedProtocols.clear();    
  config.SSID = "\"" + SSID + "\"";    
  /*//增加热点时候 如果已经存在SSID 则将SSID先删除以防止重复SSID出现  
    WifiConfiguration tempConfig = wifiAdmin.IsExsits(SSID);    
    if (tempConfig != null) {    
    settingWifimin.AdwifiManager.removeNetwork(tempConfig.networkId);     
  } */   
  // 分为三种情况:没有密码   用wep加密  用wpa加密    
  if (type == SECURITY_NONE) {   // WIFICIPHER_NOPASS    
    config.wepKeys[0] = "";    
    config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);    
    config.wepTxKeyIndex = 0;     
  } else if (type == SECURITY_WEP) {  //  WIFICIPHER_WEP     
    config.hiddenSSID = true;    
    config.wepKeys[0] = "\"" + password + "\"";    
    config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);    
    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);    
    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);    
    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);    
    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);    
    config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);    
    config.wepTxKeyIndex = 0;    
  } else if (type == SECURITY_WPA) {   // WIFICIPHER_WPA    
    config.preSharedKey = "\"" + password + "\"";    
    /*config.hiddenSSID = true;    
    config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);    
    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);    
    config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);    
    config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);     
    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);    
    config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);    
    config.status = WifiConfiguration.Status.ENABLED; */   
    config.hiddenSSID = true;      
    config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);      
    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);                            
    config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);                            
    config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);                       
    config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); 
    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    config.allowedPairwiseCiphers
      .set(WifiConfiguration.PairwiseCipher.CCMP);
    config.status = WifiConfiguration.Status.ENABLED;  
  }    
  /*config.proxySettings = ProxySettings.NONE;
  config.ipAssignment = m_ipAssignment;
  config.linkProperties = new LinkProperties(m_linkProperties);*/
  return config;    
  }

连接:


int networkId = WifiManager.addNetwork(WifiConfiguration config);
//若已存在, 无需调用, 当然, 也可调用remove
WifiManager.removeNetwork(int networkId);
//最后
WifiManager.enableNetwork(int NetworkId, boolean disableOther)


断开连接:


//获取networkId
public int getNetworkIdFromConfigByName(String name){
  int id = -1;
                List<WifiConfiguration> mWifiConfigList = WifiManager.getConfiguredNetworks();
  for(WifiConfiguration conf : mWifiConfigList){
    if(conf.SSID.equals(name)){
    return conf.networkId;
    }
  }
  return id;
  }
//删除WIFI并断开:
private boolean  RemoveWifi(int netId){
  return mWifiManager.removeNetwork(netId);
  }


蓝牙部分待续.....


相关文章
|
7月前
|
Android开发
Android 状态栏WiFi图标的显示逻辑
Android 状态栏WiFi图标的显示逻辑
171 0
|
4月前
|
Android开发
Android 配置蓝牙遥控器键值
本文详细介绍了Android系统中配置蓝牙遥控器键值的步骤,包括查看设备号、配置键位映射文件(kl文件)、部署kl文件以及调试过程,确保蓝牙遥控器的按键能正确映射到Android系统对应的按键功能。
162 1
|
6月前
|
XML API 开发工具
Android Bitmap 加载与像素操作
Android Bitmap 加载与像素操作
49 2
|
5月前
|
Android开发
Android kernel 操作gpio
Android kernel 操作gpio
53 0
|
6月前
|
存储 算法 Java
Android 进阶——代码插桩必知必会&ASM7字节码操作
Android 进阶——代码插桩必知必会&ASM7字节码操作
253 0
|
7月前
|
Android开发
Android获取当前连接的wifi名称
Android获取当前连接的wifi名称
338 6
|
7月前
|
Android开发
Android获取蓝牙设备列表的方法
Android获取蓝牙设备列表的方法
544 5
|
7月前
|
定位技术 Android开发
Android 12蓝牙报java.lang.SecurityException: Need android.permission.BLUETOOTH_CONNECT permission
Android 12蓝牙报java.lang.SecurityException: Need android.permission.BLUETOOTH_CONNECT permission
244 1
|
7月前
|
Android开发
android连接指定wifi
android连接指定wifi
107 0
|
7月前
|
Android开发 Python
Python封装ADB获取Android设备wifi地址的方法
Python封装ADB获取Android设备wifi地址的方法
155 0