美文网首页
Android之Bluetooth通信-BLE(Gatt)服务端

Android之Bluetooth通信-BLE(Gatt)服务端

作者: 锄禾豆 | 来源:发表于2022-02-24 09:10 被阅读0次
    app -- 系统服务 -- bluetooth.apk
    
    关键:
    GattService 承接服务注册和回调给服务端
    

    源码

    7.1
    

    核心代码

    frameworks/base/core/java/android/bluetooth
    BluetoothAdapter
    BluetoothLeAdvertiser
    AdvertiseSettings
    AdvertiseData
    AdvertiseCallback
    
    BluetoothManager
    BluetoothGattServer
    BluetoothGattServerCallback
    BluetoothGattService
    BluetoothGattCharacteristic
    
    packages/apps/Bluetooth/src/com/android/bluetooth/gatt
    GattService
    AdvertiseManager
    
    

    1.怎么设置广播
    1)应用

        private class BLEAdvertiser extends AdvertiseCallback {
    
            private BluetoothLeAdvertiser mBluetoothLeAdvertiser;
    
            public void startAdvertising() {
                if(mBluetoothLeAdvertiser == null) {
                    mBluetoothLeAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();//广播者的来源
                }
    
                if (mBluetoothLeAdvertiser == null) {
                    Slog.w(TAG, "Failed to create advertiser");
                    return;
                }
    
                AdvertiseSettings settings = new AdvertiseSettings.Builder()
                        .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
                        .setConnectable(true)
                        .setTimeout(0)
                        .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
                        .build();//设置配置
    
                AdvertiseData data = new AdvertiseData.Builder()
                        .setIncludeDeviceName(true)
                        .setIncludeTxPowerLevel(false)
                        .addServiceUuid(new ParcelUuid(SERVICE_UUID))
                        .build();//设置数据
    
                mBluetoothLeAdvertiser.startAdvertising(settings, data, this);//开始广播。开始是否成功由回调方法给出答复
            }
    
            public void stopAdvertising() {
                if(mBluetoothLeAdvertiser != null) {
                    mBluetoothLeAdvertiser.stopAdvertising(this);
                }
            }
    
            @Override
            public void onStartSuccess(AdvertiseSettings settingsInEffect) {//广播设置成功的回调
                if(DBG) Slog.v(TAG, "start Advertise Success info="+(settingsInEffect == null ? null : settingsInEffect.toString()));
                mState = STATE_ADVERTISE_SUCCESS;
                if(mBLEGattServer != null) {
                    mBLEGattServer.startServer();
                }
            }
    
            @Override
            public void onStartFailure(int errorCode) {//广播设置失败的回调
                mState = STATE_ADVERTISE_FAILED;
                Slog.e(TAG, "start Advertise failed,errorCode="+errorCode);
            }
        }
    

    2)源码分析。
    案例:BluetoothLeAdvertiser.startAdvertising

    a.startAdvertising

        public void startAdvertising(AdvertiseSettings settings,
                AdvertiseData advertiseData, AdvertiseData scanResponse,
                final AdvertiseCallback callback) {
            synchronized (mLeAdvertisers) {
                ······
                IBluetoothGatt gatt;
                try {
                    gatt = mBluetoothManager.getBluetoothGatt();
                } catch (RemoteException e) {
                    Log.e(TAG, "Failed to get Bluetooth gatt - ", e);
                    postStartFailure(callback, AdvertiseCallback.ADVERTISE_FAILED_INTERNAL_ERROR);
                    return;
                }
                AdvertiseCallbackWrapper wrapper = new AdvertiseCallbackWrapper(callback, advertiseData,
                        scanResponse, settings, gatt);
                wrapper.startRegisteration();//包装类的注册
            }
        }
    
    

    b.AdvertiseCallbackWrapper.startRegisteration

    private class AdvertiseCallbackWrapper extends BluetoothGattCallbackWrapper {
        
            public void startRegisteration() {
                synchronized (this) {
                    if (mClientIf == -1) return;
    
                    try {
                        UUID uuid = UUID.randomUUID();
                        mBluetoothGatt.registerClient(new ParcelUuid(uuid), this);//binder对象跨进程注册,注意回调
                        wait(LE_CALLBACK_TIMEOUT_MILLIS);//等待
                    } catch (InterruptedException | RemoteException e) {
                        Log.e(TAG, "Failed to start registeration", e);
                    }
                    ······
                }
            }
            
            /**
             * Application interface registered - app is ready to go
             */
            @Override
            public void onClientRegistered(int status, int clientIf) {//registerClient成功与失败的回调方法
                Log.d(TAG, "onClientRegistered() - status=" + status + " clientIf=" + clientIf);
                synchronized (this) {
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        try {
                            if (mClientIf == -1) {
                                // Registration succeeds after timeout, unregister client.
                                mBluetoothGatt.unregisterClient(clientIf);
                            } else {
                                mClientIf = clientIf;
                                mBluetoothGatt.startMultiAdvertising(mClientIf, mAdvertisement,
                                        mScanResponse, mSettings);//启动广播
                            }
                            return;
                        } catch (RemoteException e) {
                            Log.e(TAG, "failed to start advertising", e);
                        }
                    }
                    // Registration failed.
                    mClientIf = -1;
                    notifyAll();
                }
            }
            
            @Override
            public void onMultiAdvertiseCallback(int status, boolean isStart,
                    AdvertiseSettings settings) {
                synchronized (this) {
                    if (isStart) {
                        if (status == AdvertiseCallback.ADVERTISE_SUCCESS) {
                            // Start success
                            mIsAdvertising = true;
                            postStartSuccess(mAdvertiseCallback, settings);
                        } else {
                            // Start failure.
                            postStartFailure(mAdvertiseCallback, status);
                        }
                    } else {
                        // unregister client for stop.
                        try {
                            mBluetoothGatt.unregisterClient(mClientIf);
                            mClientIf = -1;
                            mIsAdvertising = false;
                            mLeAdvertisers.remove(mAdvertiseCallback);
                        } catch (RemoteException e) {
                            Log.e(TAG, "remote exception when unregistering", e);
                        }
                    }
                    notifyAll();
                }
    
            }
        
    }
    

    c.进入Bluetooth.apk的GattService.registerClient

    packages/apps/Bluetooth/
    com.android.bluetooth.gatt.GattService
        void registerClient(UUID uuid, IBluetoothGattCallback callback) {
            enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
    
            if (DBG) Log.d(TAG, "registerClient() - UUID=" + uuid);
            mClientMap.add(uuid, callback, this);
            gattClientRegisterAppNative(uuid.getLeastSignificantBits(),
                                        uuid.getMostSignificantBits());//回调的方法,通过jni触发
        }
        
        void onClientRegistered(int status, int clientIf, long uuidLsb, long uuidMsb)
                throws RemoteException {//jni调用回来的回调方法
            UUID uuid = new UUID(uuidMsb, uuidLsb);
            if (DBG) Log.d(TAG, "onClientRegistered() - UUID=" + uuid + ", clientIf=" + clientIf);
            ClientMap.App app = mClientMap.getByUuid(uuid);
            if (app != null) {
                if (status == 0) {
                    app.id = clientIf;
                    app.linkToDeath(new ClientDeathRecipient(clientIf));
                } else {
                    mClientMap.remove(uuid);
                }
                app.callback.onClientRegistered(status, clientIf);//binder对象跨进程调回注册app
            }
        }
    

    d.进入Bluetooth.apk的GattService.startMultiAdvertising

    packages/apps/Bluetooth/
    com.android.bluetooth.gatt.GattService
        void startMultiAdvertising(int clientIf, AdvertiseData advertiseData,
                AdvertiseData scanResponse, AdvertiseSettings settings) {
            enforceAdminPermission();
            mAdvertiseManager.startAdvertising(new AdvertiseClient(clientIf, settings, advertiseData,
                    scanResponse));
        }
        
    packages/apps/Bluetooth/
    com.android.bluetooth.gatt.AdvertiseManager
        void startAdvertising(AdvertiseClient client) {
            if (client == null) {
                return;
            }
            Message message = new Message();
            message.what = MSG_START_ADVERTISING;
            message.obj = client;
            mHandler.sendMessage(message);
        }
        
            private void handleStartAdvertising(AdvertiseClient client) {
                Utils.enforceAdminPermission(mService);
                int clientIf = client.clientIf;
                ······
                if (!mAdvertiseNative.startAdverising(client)) {//jni注册
                    postCallback(clientIf, AdvertiseCallback.ADVERTISE_FAILED_INTERNAL_ERROR);
                    return;
                }
                mAdvertiseClients.add(client);
                postCallback(clientIf, AdvertiseCallback.ADVERTISE_SUCCESS);//回调成功
            }
            
        // Post callback status to app process.
        private void postCallback(int clientIf, int status) {
            try {
                AdvertiseClient client = getAdvertiseClient(clientIf);
                AdvertiseSettings settings = (client == null) ? null : client.settings;
                boolean isStart = true;
                mService.onMultipleAdvertiseCallback(clientIf, status, isStart, settings);//回调到GattService
            } catch (RemoteException e) {
                loge("failed onMultipleAdvertiseCallback", e);
            }
        }
    
    packages/apps/Bluetooth/
    com.android.bluetooth.gatt.GattService
        // callback from AdvertiseManager for advertise status dispatch.
        void onMultipleAdvertiseCallback(int clientIf, int status, boolean isStart,
                AdvertiseSettings settings) throws RemoteException {
            ClientMap.App app = mClientMap.getById(clientIf);
            if (app == null || app.callback == null) {
                Log.e(TAG, "Advertise app or callback is null");
                return;
            }
            app.callback.onMultiAdvertiseCallback(status, isStart, settings);//binder通信调进注册app
        }
    

    e.小结

    亮点1:
    Bluetooth.apk中的GattService既作为app跨进程调用的接收方,也作为回调方法回调的处理方。这种接收和回调处理集中处理,方便了代码阅读。点赞
    
    亮点2:
    IBluetoothGattCallback中涉及的方法很多,在客户端调用时,采用了BluetoothGattCallbackWrapper模式,这样继承BluetoothGattCallbackWrapper的类,就不用全部把方法类出来。点赞
    class BluetoothGattCallbackWrapper extends IBluetoothGattCallback.Stub
    
    class AdvertiseCallbackWrapper extends BluetoothGattCallbackWrapper
    

    相关文章

      网友评论

          本文标题:Android之Bluetooth通信-BLE(Gatt)服务端

          本文链接:https://www.haomeiwen.com/subject/jhgqkrtx.html