您的位置:首页 > 移动开发 > Android开发

Android蓝牙篇:(一)基础篇

2016-06-06 22:04 405 查看
一、获取本地蓝牙设备

首先来看一下android API给出的获取方法:

To get a BluetoothAdapter representing the local Bluetooth adapter,
when running on JELLY_BEAN_MR1 and below, call the static getDefaultAdapter method;
when running on JELLY_BEAN_MR2 and higher, retrieve it through "android.content.Context.getSystemService" with "android.content.Context.BLUETOOTH_SERVICE".
Fundamentally, this is your starting point for all Bluetooth actions.

即为了使用蓝牙功能,JELLY_BEAN_MR1以下的版本使用如下方式获得BluetoothAdapter单例对象。

BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();

JELLY_BEAN_MR2以后的版本,使用如下方式来调用蓝牙API。
BluetoothManager bluetoothManager =
(BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter mAdpter=bluetoothManager.getAdapter();


这两种方式都是可以使用的,具体的区别后续会进行添加。(区别?

二、获取已配对的蓝牙适配器对象

首先来看一下android API给出的获取方法:

Once you have the local adapter, you can get a set of BluetoothDevice objects representing all paired devices with getBondedDevices(); 即通过getBondedDevices() 获得已配对设备,返回(绑定(配对)到本地蓝牙的)BluetoothDevice对象集合;

使用示例:
Set<BluetoothDevice> devices = adapter.getBondedDevices();
 if(devices.size()>0)
 {
    //用迭代
    for(Iterator iterator = devices.iterator();iterator.hasNext();)
    {
     //得到BluetoothDevice对象,也就是说得到配对的蓝牙适配器
     BluetoothDevice device = (BluetoothDevice)iterator.next();
     //得到远程蓝牙设备的地址
     Log.d("mytag",device.getAddress());
    }
 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android 蓝牙