Android 蓝牙API详解和连接使用

1.蓝牙开发有两个主要的API

BuletoothAdapter:本地蓝牙的适配器,也就是说当前应用程序所运行的Android设备上的蓝牙

BuletoothDevice  : 远程的蓝牙适配器,也就是说你要连接的Android设备的适配器。

2.蓝牙权限 :

android.permission.BLUETOOTH : 允许程序连接到已配对的蓝牙设备, 请求连接/接收连接/传输数据需要改权限, 主要用于对配对后进行操作;

android.permission.BLUETOOTH_ADMIN : 允许程序发现和配对蓝牙设备, 该权限用来管理蓝牙设备, 有了这个权限, 应用才能使用本机的蓝牙设备, 主要用于对配对前的操作;

优先级 : BLUETOOTH权限是BLUETOOTH_ADMIN权限的前提, 如果没有BLUETOOTH权限, 就不能使用BLUETOOTH_ADMIN权限;

3.蓝牙状态值:

蓝牙关闭 : int STATE_OFF , 值为10, 蓝牙模块处于关闭状态;

蓝牙打开中 : int STATE_TURNING_ON , 值为11, 蓝牙模块正在打开;

蓝牙开启 : int STATE_ON , 值为12, 蓝牙模块处于开启状态;

蓝牙开启中 : int STATE_TURNING_OFF , 值为13, 蓝牙模块正在关闭;

4.蓝牙相关的广播:

开关状态改变:

BluetoothAdapter.ACTION_STATE_CHANGE:

可以通过intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)获取当前蓝牙改变的状态。

搜索到附近可用设备:

BluetoothDevice.ACTION_FOUND:

可以通过intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 获取当前搜索到的远程设备。

配对请求:

BluetoothDevice.ACTION_PAIRING_REQUEST

5.常用方法:

BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter(); //获取本地蓝牙实例

开始 / 停止 扫描附近的设备:

mAdapter.startDiscovery(); 

获取蓝牙基本信息:

MAC地址:mAdapter.getAddress();

名称:      mAdapter.getName();

6.使用方法

6.1配置权限

<!--需要硬件支持低功耗蓝牙-->
<uses-feature android:name="android.permission.BLUETOOTH_ADMIN"/>
<!--蓝牙权限-->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<!--Android 5.0以上蓝牙好需要位置权限-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="andriod.permission.ACCESS_FINE_LOCATION"/>

6.2主要的使用方法,使用到有序广播

// 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    Log.e("=======开始进来=======", "检查当前手机不支持蓝牙");
    Toast.makeText(this, "检查当前手机不支持蓝牙", Toast.LENGTH_SHORT).show();
    finish();
}

// 初始化 Bluetooth adapter, 通过蓝牙管理器得到一个参考蓝牙适配器(API必须在以上android4.3或以上和版本)
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

// 检查设备上是否支持蓝牙
if (mBluetoothAdapter == null) {
    Log.e("=======开始进来=======", "mBluetoothAdapter=" + mBluetoothAdapter);
    Toast.makeText(this, "检查当前手机不支持蓝牙", Toast.LENGTH_SHORT).show();
    finish();
    return;
}
@Override
public void onReceive(Context context, Intent intent) {
    action = intent.getAction(); //得到action
    Log.e("===action:===", "[" + action + "]");
    if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)) {
        // Intent中获取设备对象
        btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        Log.e("===发现设备:===", "[" + btDevice.getName() + "]" + ":" + btDevice.getAddress());
        if (mLDevices.size() == 0 && !btDevice.getName().equals("null"))
            mLDevices.add(btDevice);
        else if (!mLDevices.contains(btDevice) && btDevice.getName() != null)
            mLDevices.add(btDevice);
        if (mLDevices.size() == 0) {
            rl_fail.setVisibility(View.VISIBLE);
        } else {
            pairingKey = String.valueOf(intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_KEY, BluetoothDevice.ERROR));
            rl_success.setVisibility(View.VISIBLE);
            loadData();
        }
    } else if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)) {
        sePairingRequest(btDevice);
    }
}
private void setFound(BluetoothDevice bDevice) {
    /**
     * 发现设备
     */
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        Log.e("===发现设备:===", "[" + bDevice.getName() + "]" + ":" + bDevice.getAddress());
        /**
         * 设备如果有多个,第一个搜到的那个会被尝试。
         */
        if (bDevice.getName() != null && bDevice.getName().contains(BLUETOOTHNAME)) {
            if (bDevice.getBondState() == BluetoothDevice.BOND_NONE) {

                Log.e("===ywq===", "attemp to bond:" + "[" + bDevice.getName() + "]");
                try {
                    //通过工具类ClsUtils,调用createBond方法
                    btDevice = bDevice;
                    ClsUtils.createBond(bDevice.getClass(), bDevice);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        } else
            Log.e("===error===", "Is faild");
    }
}

private void sePairingRequest(BluetoothDevice bDevice) {
    if (action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST)) { //再次得到的action,会等于PAIRING_REQUEST
        Log.e("===action2===", action);
        if (bDevice.getName().contains("iPhone")) {
            Log.e("===here===", "OKOKOK");
            try {
                //1.确认配对
                ClsUtils.setPairingConfirmation(bDevice.getClass(), bDevice, true);
                //2.调用setPin方法进行配对...
                boolean ret = ClsUtils.setPin(bDevice.getClass(), bDevice, String.valueOf(pairingKey));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else
            Log.e("提示信息===", "这个设备不是目标蓝牙设备");
    }
}

Demo下载地址:https://download.csdn.net/download/qq_39735504/10324973

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值