码迷,mamicode.com
首页 > 移动开发 > 详细

Android 扫描蓝牙设备

时间:2015-10-18 12:49:46      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

Android扫描蓝牙设备是个异步的过程,核心的步骤为:调用bluetoothAdapter的startDiscovery()进行设备扫描,扫描的结果通过广播接收处理!具体如下:

1.申请相关权限

1 <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
2     <uses-permission android:name="android.permission.BLUETOOTH"/>

2.注册广播

1 private void registerBroadcast() {
2         // Register for broadcasts when a device is discovered
3         IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
4         mContext.registerReceiver(mReceiver, filter);
5 
6         // Register for broadcasts when discovery has finished
7         filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
8         mContext.registerReceiver(mReceiver, filter);
9     }

3.扫描设备

1 private void doDiscovery() {
2         // If we‘re already discovering, stop it
3         if (mBluetoothAdapter.isDiscovering()) {
4             mBluetoothAdapter.cancelDiscovery();
5         }
6         // Request discover from BluetoothAdapter
7         mBluetoothAdapter.startDiscovery();
8     }

4.广播中处理扫描到的设备

 1 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
 2         @Override
 3         public void onReceive(Context context, Intent intent) {
 4             String action = intent.getAction();
 5             
 6             if (BluetoothDevice.ACTION_FOUND.equals(action)) {
 7                 // TODO discovery finds a device
 8                 
 9             } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
10                     .equals(action)) {
11                 // TODO discovery is finished
12             }
13         }
14     };

 

Android 扫描蓝牙设备

标签:

原文地址:http://www.cnblogs.com/pillowzhou/p/4889218.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!