Android(蓝牙)

因近期项目需求调试了Android蓝牙通讯接口,主要是两个终端作为服务端和客户端的通信,本文将部分重要知识点记录如下。

蓝牙是短距离无线通信,通常分经典蓝牙和低功耗蓝牙(即蓝牙4.0),两类蓝牙协议各层定义上存在很多不同,因此芯片也不一样,但就Android上做应用层开发没什么差别。

蓝牙通信分为配对和数据传输两部分,两部分是独立的,一般来说是点对点,如果要组局域网需要支持LAN协议扩展,没有尝试过。

  • 配对阶段
    • 发现设备方
           
       mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mBluetoothAdapter.enable(); IntentFilter intent = new IntentFilter(); intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果 receiver = new BluetoothReceiver(); registerReceiver(receiver, intent);//注册一个广播,接收蓝牙设备发现的消息 mBluetoothAdapter.startDiscovery();
    private class BluetoothReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action))
            {
                if(isFound == true){
                    return;
                }
                isFound = true;
                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//获取这个蓝牙设备,可能存在多个
    • 被发现方
        Intent discoveryIntent = new Intent(
                BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
                300);//弹出一个窗口,确认本机蓝牙设备在300s内可被发现
        discoveryIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(discoveryIntent);
  • 通信阶段

通信阶段基本等价于socket编程,本文不黏贴全部代码,唯一遇到的问题是不用反射方法获取设备,通信连接很不稳定,本文代码如下:

    • 服务器端
Method listenMethod = adapter.getClass().getMethod("listenUsingRfcommOn", new Class[]{int.class});
mmServerSocket = ( BluetoothServerSocket) listenMethod.invoke(adapter, Integer.valueOf(1));
socket = mmServerSocket.accept();
    • 客户端
Method method = mServerDevice.getClass().getMethod("createRfcommSocket",new Class[] { int.class });
mSocket = (BluetoothSocket) method.invoke(mServerDevice, Integer.valueOf(1));
原文地址:https://www.cnblogs.com/Fredric-2013/p/4612819.html