Android 蓝牙通信及WiFi开发

柔光的暖阳◎ 2022-09-29 14:51 531阅读 0赞

在我们正常的Android蓝牙功能开发步骤中,一般要经过系统权限和蓝牙开关状态监测、设备扫描、设备连接、蓝牙数据通信这几个过程。
在Android 4.3系统之后,我们可以使用蓝牙4.0(低功耗蓝牙),它最主要的特点是低功耗,普及率高。现在所说的蓝牙设备,大部分都是在说4.0设备,ble也特指4.0设备。 在4.0之前重要的版本有2.1版本-基本速率/增强数据率(BR/EDR)和3.0 高速蓝牙版本,这些统称为经典蓝牙。

如果想让支持低功耗蓝牙的设备使用蓝牙4.0,我们可以通过如下代码去监测

  1. // AndroidManifest.xml
  2. <uses-feature android:name="android.hardware.bluetooth_le" android:required="false"/>
  3. if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
  4. Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
  5. finish();
  6. }

权限监测

首先我们必须要给予应用相应的蓝牙权限。

  1. //需要此权限来执行任何蓝牙通信,如请求一个连接、接受一个连接和传输数据。
  2. <uses-permission android:name="android.permission.BLUETOOTH"/>
  3. //如果你想让你的应用启动设备发现或操纵蓝牙设置,必须申报bluetooth_admin许可
  4. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

然后在程序启动时监测当前设备是否已经打开蓝牙,若没打开则跳转到系统蓝牙功能开关界面选择开启蓝牙

  1. // If BT is not on, request that it be enabled.
  2. // setupChat() will then be called during onActivityResult
  3. if (!mBluetoothAdapter.isEnabled()) {
  4. Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  5. startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
  6. // Otherwise, setup the chat session
  7. } else if (mChatService == null) {
  8. setupChat();
  9. }

在onActivityResult中捕获

  1. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  2. switch (requestCode) {
  3. case REQUEST_ENABLE_BT:
  4. // When the request to enable Bluetooth returns
  5. if (resultCode == Activity.RESULT_OK) {
  6. // Bluetooth is now enabled, so set up a chat session
  7. setupChat();
  8. } else {
  9. // User did not enable Bluetooth or an error occurred
  10. Log.d(TAG, "BT not enabled");
  11. Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving,
  12. Toast.LENGTH_SHORT).show();
  13. getActivity().finish();
  14. }
  15. }
  16. }

设备扫描

我们只需要调用BluetoothAdapter的startDiscovery()方法,便开始搜索附近的其他蓝牙设备,

  1. /**
  2. * Start device discover with the BluetoothAdapter
  3. */
  4. private void doDiscovery() {
  5. // If we're already discovering, stop it
  6. if (mBtAdapter.isDiscovering()) {
  7. mBtAdapter.cancelDiscovery();
  8. }
  9. // Request discover from BluetoothAdapter
  10. mBtAdapter.startDiscovery();
  11. }

之后,如果搜索到一个蓝牙设备,系统就是发出一个广播,我们可以对它进行接收并且进行相应的处理:

  1. // Register for broadcasts when a device is discovered
  2. IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  3. this.registerReceiver(mReceiver, filter);
  4. // Register for broadcasts when discovery has finished
  5. filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  6. this.registerReceiver(mReceiver, filter);
  7. /**
  8. * The BroadcastReceiver that listens for discovered devices and changes the title when
  9. * discovery is finished
  10. */
  11. private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
  12. @Override
  13. public void onReceive(Context context, Intent intent) {
  14. String action = intent.getAction();
  15. // When discovery finds a device
  16. if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  17. // Get the BluetoothDevice object from the Intent
  18. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  19. // If it's already paired, skip it, because it's been listed already
  20. if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
  21. mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
  22. }
  23. // When discovery is finished, change the Activity title
  24. } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
  25. setProgressBarIndeterminateVisibility(false);
  26. setTitle(R.string.select_device);
  27. if (mNewDevicesArrayAdapter.getCount() == 0) {
  28. //do something here after finished discovery
  29. }
  30. }
  31. }
  32. };

连接

在搜索到的其它设备里选择一个需要连接通信的设备,传入设备的地址,调用getRemoteDevice方法去获得一个BluetoothDevice 实例,然后开辟一个子线程用于建立连接,

  1. private void connectDevice(Intent data, boolean secure) {
  2. // Get the device MAC address
  3. String address = data.getExtras()
  4. .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
  5. // Get the BluetoothDevice object
  6. BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
  7. // Attempt to connect to the device
  8. mChatService.connect(device, secure);
  9. }
  10. /**
  11. * Start the ConnectThread to initiate a connection to a remote device.
  12. *
  13. * @param device The BluetoothDevice to connect
  14. * @param secure Socket Security type - Secure (true) , Insecure (false)
  15. */
  16. public synchronized void connect(BluetoothDevice device, boolean secure) {
  17. Log.d(TAG, "connect to: " + device);
  18. // Cancel any thread attempting to make a connection
  19. if (mState == STATE_CONNECTING) {
  20. if (mConnectThread != null) {
  21. mConnectThread.cancel();
  22. mConnectThread = null;
  23. }
  24. }
  25. // Cancel any thread currently running a connection
  26. if (mConnectedThread != null) {
  27. mConnectedThread.cancel();
  28. mConnectedThread = null;
  29. }
  30. // Start the thread to connect with the given device
  31. mConnectThread = new ConnectThread(device, secure);
  32. mConnectThread.start();
  33. // Update UI
  34. }

连接线程:此处调用了device.createRfcommSocketToServiceRecord方法去创建一个用于通信的socket,参数是UUID,是一个通用标识符。

  1. private class ConnectThread extends Thread {
  2. private final BluetoothSocket mmSocket;
  3. private final BluetoothDevice mmDevice;
  4. private String mSocketType;
  5. public ConnectThread(BluetoothDevice device, boolean secure) {
  6. mmDevice = device;
  7. BluetoothSocket tmp = null;
  8. mSocketType = secure ? "Secure" : "Insecure";
  9. // Get a BluetoothSocket for a connection with the
  10. // given BluetoothDevice
  11. try {
  12. if (secure) {
  13. tmp = device.createRfcommSocketToServiceRecord(
  14. MY_UUID_SECURE);
  15. } else {
  16. tmp = device.createInsecureRfcommSocketToServiceRecord(
  17. MY_UUID_INSECURE);
  18. }
  19. } catch (IOException e) {
  20. Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
  21. }
  22. mmSocket = tmp;
  23. mState = STATE_CONNECTING;
  24. }
  25. public void run() {
  26. Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
  27. setName("ConnectThread" + mSocketType);
  28. // Always cancel discovery because it will slow down a connection
  29. mAdapter.cancelDiscovery();
  30. // Make a connection to the BluetoothSocket
  31. try {
  32. // This is a blocking call and will only return on a
  33. // successful connection or an exception
  34. mmSocket.connect();
  35. } catch (IOException e) {
  36. // Close the socket
  37. try {
  38. mmSocket.close();
  39. } catch (IOException e2) {
  40. Log.e(TAG, "unable to close() " + mSocketType +
  41. " socket during connection failure", e2);
  42. }
  43. connectionFailed();
  44. return;
  45. }
  46. // Reset the ConnectThread because we're done
  47. synchronized (BluetoothChatService.this) {
  48. mConnectThread = null;
  49. }
  50. // Start the connected thread
  51. connected(mmSocket, mmDevice, mSocketType);
  52. }
  53. public void cancel() {
  54. try {
  55. mmSocket.close();
  56. } catch (IOException e) {
  57. Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
  58. }
  59. }
  60. }

设备连接完成后,要取消连接线程,防止造成资源的浪费,然后创建通信线程,维持输入输出流的接收和发送。

  1. public synchronized void connected(BluetoothSocket socket, BluetoothDevice
  2. device, final String socketType) {
  3. Log.d(TAG, "connected, Socket Type:" + socketType);
  4. // Cancel the thread that completed the connection
  5. if (mConnectThread != null) {
  6. mConnectThread.cancel();
  7. mConnectThread = null;
  8. }
  9. // Start the thread to manage the connection and perform transmissions
  10. mConnectedThread = new ConnectedThread(socket, socketType);
  11. mConnectedThread.start();
  12. // Send the name of the connected device back to the UI Activity
  13. Message msg = mHandler.obtainMessage(Constants.MESSAGE_DEVICE_NAME);
  14. Bundle bundle = new Bundle();
  15. bundle.putString(Constants.DEVICE_NAME, device.getName());
  16. msg.setData(bundle);
  17. mHandler.sendMessage(msg);
  18. // Update UI title
  19. updateUserInterfaceTitle();
  20. }

消息传输线程:run方法是一个while循环,当处于连接状态时,会一直从输入流中获取数据,并将获取到的字节数据通过handle机制传输到主线程并显示。在需要发送数据时,只要调用write方法即可。

  1. /**
  2. * This thread runs during a connection with a remote device.
  3. * It handles all incoming and outgoing transmissions.
  4. */
  5. private class ConnectedThread extends Thread {
  6. private final BluetoothSocket mmSocket;
  7. private final InputStream mmInStream;
  8. private final OutputStream mmOutStream;
  9. public ConnectedThread(BluetoothSocket socket, String socketType) {
  10. Log.d(TAG, "create ConnectedThread: " + socketType);
  11. mmSocket = socket;
  12. InputStream tmpIn = null;
  13. OutputStream tmpOut = null;
  14. // Get the BluetoothSocket input and output streams
  15. try {
  16. tmpIn = socket.getInputStream();
  17. tmpOut = socket.getOutputStream();
  18. } catch (IOException e) {
  19. Log.e(TAG, "temp sockets not created", e);
  20. }
  21. mmInStream = tmpIn;
  22. mmOutStream = tmpOut;
  23. mState = STATE_CONNECTED;
  24. }
  25. public void run() {
  26. Log.i(TAG, "BEGIN mConnectedThread");
  27. byte[] buffer = new byte[1024];
  28. int bytes;
  29. // Keep listening to the InputStream while connected
  30. while (mState == STATE_CONNECTED) {
  31. try {
  32. // Read from the InputStream
  33. bytes = mmInStream.read(buffer);
  34. // Send the obtained bytes to the UI Activity
  35. mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
  36. .sendToTarget();
  37. } catch (IOException e) {
  38. Log.e(TAG, "disconnected", e);
  39. connectionLost();
  40. break;
  41. }
  42. }
  43. }
  44. /**
  45. * Write to the connected OutStream.
  46. *
  47. * @param buffer The bytes to write
  48. */
  49. public void write(byte[] buffer) {
  50. try {
  51. mmOutStream.write(buffer);
  52. // Share the sent message back to the UI Activity
  53. mHandler.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer)
  54. .sendToTarget();
  55. } catch (IOException e) {
  56. Log.e(TAG, "Exception during write", e);
  57. }
  58. }
  59. public void cancel() {
  60. try {
  61. mmSocket.close();
  62. } catch (IOException e) {
  63. Log.e(TAG, "close() of connect socket failed", e);
  64. }
  65. }
  66. }

至此,通过蓝牙实现数据传输的过程基本建立完毕。此处是针对普通蓝牙的通信方式,若使用低功耗蓝牙,可详见Google的官方sample:
android-BuletoothLeGatt

AndroidWiFi学习

一、WiFi相关知识

Android WiFi开发需掌握基本的操作,包括扫描附近WiFi、控制WiFi的开闭、发射WiFi热点等。
在Android的sdk中, WiFi相关的操作类都在Android.net.wifi包里面。接下来就跟随官方Guide来学习Android中WiFi的基本操作。
Google开发者中国网站api

其中主要的类有ScanResult ,wifiConfiguration, WifiInfo ,WifiManager。

ScanResult

主要用来描述已经检测出的接入点,包括接入点的地址,接入点的名称,身份认证,频率,信号强度等信息。
打开这个类,我们可以看到以下几个信息

  • BSSID 接入点的地址,这里主要是指小范围几个无线设备相连接所获取的地址,比如说两台笔记本通过无线网卡进行连接,双方的无线网卡分配的地址。
  • SSID 网络的名字,当我们搜索一个网络时,就是靠这个来区分每个不同的网络接入点。
  • Capabilities 网络接入的性能,这里主要是来判断网络的加密方式等。
  • Frequency 频率,每一个频道交互的MHz 数。
  • Level 等级,主要来判断网络连接的优先数。

wifiConfiguration

包括以下六个子类:

  • WifiConfiguration.AuthAlgorthm 用来判断加密方法。
  • WifiConfiguration.GroupCipher 获取使用GroupCipher 的方法来进行加密。
  • WifiConfiguration.KeyMgmt 获取使用KeyMgmt 进行。
  • WifiConfiguration.PairwiseCipher 获取使用WPA 方式的加密。
  • WifiConfiguration.Protocol 获取使用哪一种协议进行加密。
  • wifiConfiguration.Status 获取当前网络的状态。

WifiInfo

在我们的wifi 已经连通了以后,可以通过这个类获得一些已经连通的wifi 连接的信息获取当前链接的信息.

  • getBSSID(): 获取BSSID
  • getDetailedStateOf() : 获取客户端的连通性
  • getHiddenSSID() : 获得SSID 是否被隐藏
  • getIpAddress() : 获取IP 地址
  • getLinkSpeed() : 获得连接的速度
  • getMacAddress() : 获得Mac 地址
  • getRssi() 获得802.11n : 网络的信号
  • getSSID() : 获得SSID
  • getSupplicanState() : 返回具体客户端状态的信息

wifiManager

这个类提供了WiFi连接的管理功能,我们可以调用Context.getSystemService(Context.WIFI_SERVICE)来获取,常用方法如下:

  • addNetwork(WifiConfiguration config) 通过获取到的网络的链接状态信息,来添加网络
  • calculateSignalLevel(int rssi , int numLevels) 计算信号的等级
  • compareSignalLevel(int rssiA, int rssiB) 对比连接A 和连接B
  • createWifiLock(int lockType, String tag) 创建一个wifi 锁,锁定当前的wifi 连接
  • disableNetwork(int netId) 让一个网络连接失效
  • disconnect() 断开连接
  • enableNetwork(int netId, Boolean disableOthers) 连接一个连接
  • getConfiguredNetworks() 获取网络连接的状态
  • getConnectionInfo() 获取当前连接的信息
  • getDhcpInfo() 获取DHCP 的信息
  • getScanResulats() 获取扫描测试的结果
  • getWifiState() 获取一个wifi 接入点是否有效
  • isWifiEnabled() 判断一个wifi 连接是否有效
  • pingSupplicant() ping 一个连接,判断是否能连通
  • ressociate() 即便连接没有准备好,也要连通
  • reconnect() 如果连接准备好了,连通
  • removeNetwork() 移除某一个网络
  • saveConfiguration() 保留一个配置信息
  • setWifiEnabled() 让一个连接有效
  • startScan() 开始扫描
  • updateNetwork(WifiConfiguration config) 更新一个网络连接的信息
    详细api见官方api

二、WiFi功能使用

配置WiFi权限

  1. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
  2. <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>

WiFi管理类

这是从网上整理的一个WiFi相关的工具类,WiFi开发的很多场景需要用到的方法都在里面实现了。

  1. /**
  2. * WIFI管理类
  3. * @author ZHF
  4. *
  5. */
  6. public class WifiAdmin {
  7. private static WifiAdmin wifiAdmin = null;
  8. private List<WifiConfiguration> mWifiConfiguration; //无线网络配置信息类集合(网络连接列表)
  9. private List<ScanResult> mWifiList; //检测到接入点信息类 集合
  10. //描述任何Wifi连接状态
  11. private WifiInfo mWifiInfo;
  12. WifiManager.WifiLock mWifilock; //能够阻止wifi进入睡眠状态,使wifi一直处于活跃状态
  13. public WifiManager mWifiManager;
  14. /**
  15. * 获取该类的实例(懒汉)
  16. * @param context
  17. * @return
  18. */
  19. public static WifiAdmin getInstance(Context context) {
  20. if(wifiAdmin == null) {
  21. wifiAdmin = new WifiAdmin(context);
  22. return wifiAdmin;
  23. }
  24. return null;
  25. }
  26. private WifiAdmin(Context context) {
  27. //获取系统Wifi服务 WIFI_SERVICE
  28. this.mWifiManager = (WifiManager) context.getSystemService("wifi");
  29. //获取连接信息
  30. this.mWifiInfo = this.mWifiManager.getConnectionInfo();
  31. }
  32. /**
  33. * 是否存在网络信息
  34. * @param str 热点名称
  35. * @return
  36. */
  37. private WifiConfiguration isExsits(String str) {
  38. Iterator localIterator = this.mWifiManager.getConfiguredNetworks().iterator();
  39. WifiConfiguration localWifiConfiguration;
  40. do {
  41. if(!localIterator.hasNext()) return null;
  42. localWifiConfiguration = (WifiConfiguration) localIterator.next();
  43. }while(!localWifiConfiguration.SSID.equals("\"" + str + "\""));
  44. return localWifiConfiguration;
  45. }
  46. /**锁定WifiLock,当下载大文件时需要锁定 **/
  47. public void AcquireWifiLock() {
  48. this.mWifilock.acquire();
  49. }
  50. /**创建一个WifiLock**/
  51. public void CreateWifiLock() {
  52. this.mWifilock = this.mWifiManager.createWifiLock("Test");
  53. }
  54. /**解锁WifiLock**/
  55. public void ReleaseWifilock() {
  56. if(mWifilock.isHeld()) { //判断时候锁定
  57. mWifilock.acquire();
  58. }
  59. }
  60. /**打开Wifi**/
  61. public void OpenWifi() {
  62. if(!this.mWifiManager.isWifiEnabled()){ //当前wifi不可用
  63. this.mWifiManager.setWifiEnabled(true);
  64. }
  65. }
  66. /**关闭Wifi**/
  67. public void closeWifi() {
  68. if(mWifiManager.isWifiEnabled()) {
  69. mWifiManager.setWifiEnabled(false);
  70. }
  71. }
  72. /**端口指定id的wifi**/
  73. public void disconnectWifi(int paramInt) {
  74. this.mWifiManager.disableNetwork(paramInt);
  75. }
  76. /**添加指定网络**/
  77. public void addNetwork(WifiConfiguration paramWifiConfiguration) {
  78. int i = mWifiManager.addNetwork(paramWifiConfiguration);
  79. mWifiManager.enableNetwork(i, true);
  80. }
  81. /**
  82. * 连接指定配置好的网络
  83. * @param index 配置好网络的ID
  84. */
  85. public void connectConfiguration(int index) {
  86. // 索引大于配置好的网络索引返回
  87. if (index > mWifiConfiguration.size()) {
  88. return;
  89. }
  90. //连接配置好的指定ID的网络
  91. mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true);
  92. }
  93. /**
  94. * 根据wifi信息创建或关闭一个热点
  95. * @param paramWifiConfiguration
  96. * @param paramBoolean 关闭标志
  97. */
  98. public void createWifiAP(WifiConfiguration paramWifiConfiguration,boolean paramBoolean) {
  99. try {
  100. Class localClass = this.mWifiManager.getClass();
  101. Class[] arrayOfClass = new Class[2];
  102. arrayOfClass[0] = WifiConfiguration.class;
  103. arrayOfClass[1] = Boolean.TYPE;
  104. Method localMethod = localClass.getMethod("setWifiApEnabled",arrayOfClass);
  105. WifiManager localWifiManager = this.mWifiManager;
  106. Object[] arrayOfObject = new Object[2];
  107. arrayOfObject[0] = paramWifiConfiguration;
  108. arrayOfObject[1] = Boolean.valueOf(paramBoolean);
  109. localMethod.invoke(localWifiManager, arrayOfObject);
  110. return;
  111. } catch (Exception e) {
  112. e.printStackTrace();
  113. }
  114. }
  115. /**
  116. * 创建一个wifi信息
  117. * @param ssid 名称
  118. * @param passawrd 密码
  119. * @param paramInt 有3个参数,1是无密码,2是简单密码,3是wap加密
  120. * @param type 是"ap"还是"wifi"
  121. * @return
  122. */
  123. public WifiConfiguration createWifiInfo(String ssid, String passawrd,int paramInt, String type) {
  124. //配置网络信息类
  125. WifiConfiguration localWifiConfiguration1 = new WifiConfiguration();
  126. //设置配置网络属性
  127. localWifiConfiguration1.allowedAuthAlgorithms.clear();
  128. localWifiConfiguration1.allowedGroupCiphers.clear();
  129. localWifiConfiguration1.allowedKeyManagement.clear();
  130. localWifiConfiguration1.allowedPairwiseCiphers.clear();
  131. localWifiConfiguration1.allowedProtocols.clear();
  132. if(type.equals("wt")) { //wifi连接
  133. localWifiConfiguration1.SSID = ("\"" + ssid + "\"");
  134. WifiConfiguration localWifiConfiguration2 = isExsits(ssid);
  135. if(localWifiConfiguration2 != null) {
  136. mWifiManager.removeNetwork(localWifiConfiguration2.networkId); //从列表中删除指定的网络配置网络
  137. }
  138. if(paramInt == 1) { //没有密码
  139. localWifiConfiguration1.wepKeys[0] = "";
  140. localWifiConfiguration1.allowedKeyManagement.set(0);
  141. localWifiConfiguration1.wepTxKeyIndex = 0;
  142. } else if(paramInt == 2) { //简单密码
  143. localWifiConfiguration1.hiddenSSID = true;
  144. localWifiConfiguration1.wepKeys[0] = ("\"" + passawrd + "\"");
  145. } else { //wap加密
  146. localWifiConfiguration1.preSharedKey = ("\"" + passawrd + "\"");
  147. localWifiConfiguration1.hiddenSSID = true;
  148. localWifiConfiguration1.allowedAuthAlgorithms.set(0);
  149. localWifiConfiguration1.allowedGroupCiphers.set(2);
  150. localWifiConfiguration1.allowedKeyManagement.set(1);
  151. localWifiConfiguration1.allowedPairwiseCiphers.set(1);
  152. localWifiConfiguration1.allowedGroupCiphers.set(3);
  153. localWifiConfiguration1.allowedPairwiseCiphers.set(2);
  154. }
  155. }else {
  156. //"ap" wifi热点
  157. localWifiConfiguration1.SSID = ssid;
  158. localWifiConfiguration1.allowedAuthAlgorithms.set(1);
  159. localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
  160. localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
  161. localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
  162. localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
  163. localWifiConfiguration1.allowedKeyManagement.set(0);
  164. localWifiConfiguration1.wepTxKeyIndex = 0;
  165. if (paramInt == 1) { //没有密码
  166. localWifiConfiguration1.wepKeys[0] = "";
  167. localWifiConfiguration1.allowedKeyManagement.set(0);
  168. localWifiConfiguration1.wepTxKeyIndex = 0;
  169. } else if (paramInt == 2) { //简单密码
  170. localWifiConfiguration1.hiddenSSID = true;//网络上不广播ssid
  171. localWifiConfiguration1.wepKeys[0] = passawrd;
  172. } else if (paramInt == 3) {
  173. //wap加密
  174. localWifiConfiguration1.preSharedKey = passawrd;
  175. localWifiConfiguration1.allowedAuthAlgorithms.set(0);
  176. localWifiConfiguration1.allowedProtocols.set(1);
  177. localWifiConfiguration1.allowedProtocols.set(0);
  178. localWifiConfiguration1.allowedKeyManagement.set(1);
  179. localWifiConfiguration1.allowedPairwiseCiphers.set(2);
  180. localWifiConfiguration1.allowedPairwiseCiphers.set(1);
  181. }
  182. }
  183. return localWifiConfiguration1;
  184. }
  185. /**获取热点名**/
  186. public String getApSSID() {
  187. try {
  188. Method localMethod = this.mWifiManager.getClass().getDeclaredMethod("getWifiApConfiguration", new Class[0]);
  189. if (localMethod == null) return null;
  190. Object localObject1 = localMethod.invoke(this.mWifiManager,new Object[0]);
  191. if (localObject1 == null) return null;
  192. WifiConfiguration localWifiConfiguration = (WifiConfiguration) localObject1;
  193. if (localWifiConfiguration.SSID != null) return localWifiConfiguration.SSID;
  194. Field localField1 = WifiConfiguration.class .getDeclaredField("mWifiApProfile");
  195. if (localField1 == null) return null;
  196. localField1.setAccessible(true);
  197. Object localObject2 = localField1.get(localWifiConfiguration);
  198. localField1.setAccessible(false);
  199. if (localObject2 == null) return null;
  200. Field localField2 = localObject2.getClass().getDeclaredField("SSID");
  201. localField2.setAccessible(true);
  202. Object localObject3 = localField2.get(localObject2);
  203. if (localObject3 == null) return null;
  204. localField2.setAccessible(false);
  205. String str = (String) localObject3;
  206. return str;
  207. } catch (Exception localException) {
  208. }
  209. return null;
  210. }
  211. /**获取wifi名**/
  212. public String getBSSID() {
  213. if (this.mWifiInfo == null)
  214. return "NULL";
  215. return this.mWifiInfo.getBSSID();
  216. }
  217. /**得到配置好的网络 **/
  218. public List<WifiConfiguration> getConfiguration() {
  219. return this.mWifiConfiguration;
  220. }
  221. /**获取ip地址**/
  222. public int getIPAddress() {
  223. return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
  224. }
  225. /**获取物理地址(Mac)**/
  226. public String getMacAddress() {
  227. return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
  228. }
  229. /**获取网络id**/
  230. public int getNetworkId() {
  231. return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
  232. }
  233. /**获取热点创建状态**/
  234. public int getWifiApState() {
  235. try {
  236. int i = ((Integer) this.mWifiManager.getClass()
  237. .getMethod("getWifiApState", new Class[0])
  238. .invoke(this.mWifiManager, new Object[0])).intValue();
  239. return i;
  240. } catch (Exception localException) {
  241. }
  242. return 4; //未知wifi网卡状态
  243. }
  244. /**获取wifi连接信息**/
  245. public WifiInfo getWifiInfo() {
  246. return this.mWifiManager.getConnectionInfo();
  247. }
  248. /** 得到网络列表**/
  249. public List<ScanResult> getWifiList() {
  250. return this.mWifiList;
  251. }
  252. /**查看扫描结果**/
  253. public StringBuilder lookUpScan() {
  254. StringBuilder localStringBuilder = new StringBuilder();
  255. for (int i = 0; i < mWifiList.size(); i++)
  256. {
  257. localStringBuilder.append("Index_"+new Integer(i + 1).toString() + ":");
  258. //将ScanResult信息转换成一个字符串包
  259. //其中把包括:BSSID、SSID、capabilities、frequency、level
  260. localStringBuilder.append((mWifiList.get(i)).toString());
  261. localStringBuilder.append("\n");
  262. }
  263. return localStringBuilder;
  264. }
  265. /** 设置wifi搜索结果 **/
  266. public void setWifiList() {
  267. this.mWifiList = this.mWifiManager.getScanResults();
  268. }
  269. /**开始搜索wifi**/
  270. public void startScan() {
  271. this.mWifiManager.startScan();
  272. }
  273. /**得到接入点的BSSID**/
  274. public String GetBSSID() {
  275. return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
  276. }
  277. }

WiFi热点的创建

创建WiFi热点需要先获取到wifi的服务,再配置热点名称、密码等等,然后再通过反射调用setWifiApEnabled方法来创建热点。因为wifi和热点不能同时打开,所以打开热点的时候需要调用wifiManager.setWifiEnabled(false); 关闭wifi

  1. public void stratWifiAp() {
  2. Method method1 = null;
  3. try {
  4. method1 = mWifiManager.getClass().getMethod("setWifiApEnabled",
  5. WifiConfiguration.class, boolean.class);
  6. WifiConfiguration netConfig = new WifiConfiguration();
  7. netConfig.SSID = mSSID;
  8. netConfig.preSharedKey = mPasswd;
  9. netConfig.allowedAuthAlgorithms
  10. .set(WifiConfiguration.AuthAlgorithm.OPEN);
  11. netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
  12. netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
  13. netConfig.allowedKeyManagement
  14. .set(WifiConfiguration.KeyMgmt.WPA_PSK);
  15. netConfig.allowedPairwiseCiphers
  16. .set(WifiConfiguration.PairwiseCipher.CCMP);
  17. netConfig.allowedPairwiseCiphers
  18. .set(WifiConfiguration.PairwiseCipher.TKIP);
  19. netConfig.allowedGroupCiphers
  20. .set(WifiConfiguration.GroupCipher.CCMP);
  21. netConfig.allowedGroupCiphers
  22. .set(WifiConfiguration.GroupCipher.TKIP);
  23. method1.invoke(mWifiManager, netConfig, true);
  24. } catch (IllegalArgumentException e) {
  25. // TODO Auto-generated catch block
  26. e.printStackTrace();
  27. } catch (IllegalAccessException e) {
  28. // TODO Auto-generated catch block
  29. e.printStackTrace();
  30. } catch (InvocationTargetException e) {
  31. // TODO Auto-generated catch block
  32. e.printStackTrace();
  33. } catch (SecurityException e) {
  34. // TODO Auto-generated catch block
  35. e.printStackTrace();
  36. } catch (NoSuchMethodException e) {
  37. // TODO Auto-generated catch block
  38. e.printStackTrace();
  39. }
  40. }

参考文章:
Android开发之蓝牙通信
Android BulutoothChat
Android中WiFi开发总结

发表评论

表情:
评论列表 (有 0 条评论,531人围观)

还没有评论,来说两句吧...

相关阅读