Android之Bluetooth通信-BLE(Gatt)服務(wù)端分析

app -- 系統(tǒng)服務(wù) -- bluetooth.apk

關(guān)鍵:
GattService 承接服務(wù)注冊(cè)和回調(diào)給服務(wù)端

源碼

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.怎么設(shè)置廣播
1)應(yīng)用

    private class BLEAdvertiser extends AdvertiseCallback {

        private BluetoothLeAdvertiser mBluetoothLeAdvertiser;

        public void startAdvertising() {
            if(mBluetoothLeAdvertiser == null) {
                mBluetoothLeAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();//廣播者的來(lái)源
            }

            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();//設(shè)置配置

            AdvertiseData data = new AdvertiseData.Builder()
                    .setIncludeDeviceName(true)
                    .setIncludeTxPowerLevel(false)
                    .addServiceUuid(new ParcelUuid(SERVICE_UUID))
                    .build();//設(shè)置數(shù)據(jù)

            mBluetoothLeAdvertiser.startAdvertising(settings, data, this);//開(kāi)始廣播。開(kāi)始是否成功由回調(diào)方法給出答復(fù)
        }

        public void stopAdvertising() {
            if(mBluetoothLeAdvertiser != null) {
                mBluetoothLeAdvertiser.stopAdvertising(this);
            }
        }

        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {//廣播設(shè)置成功的回調(diào)
            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) {//廣播設(shè)置失敗的回調(diào)
            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();//包裝類的注冊(cè)
        }
    }

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對(duì)象跨進(jìn)程注冊(cè),注意回調(diào)
                    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成功與失敗的回調(diào)方法
            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);//啟動(dòng)廣播
                        }
                        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.進(jìn)入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());//回調(diào)的方法,通過(guò)jni觸發(fā)
    }
    
    void onClientRegistered(int status, int clientIf, long uuidLsb, long uuidMsb)
            throws RemoteException {//jni調(diào)用回來(lái)的回調(diào)方法
        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對(duì)象跨進(jìn)程調(diào)回注冊(cè)app
        }
    }

d.進(jìn)入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注冊(cè)
                postCallback(clientIf, AdvertiseCallback.ADVERTISE_FAILED_INTERNAL_ERROR);
                return;
            }
            mAdvertiseClients.add(client);
            postCallback(clientIf, AdvertiseCallback.ADVERTISE_SUCCESS);//回調(diào)成功
        }
        
    // 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);//回調(diào)到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通信調(diào)進(jìn)注冊(cè)app
    }

e.小結(jié)

亮點(diǎn)1:
Bluetooth.apk中的GattService既作為app跨進(jìn)程調(diào)用的接收方,也作為回調(diào)方法回調(diào)的處理方。這種接收和回調(diào)處理集中處理,方便了代碼閱讀。點(diǎn)贊

亮點(diǎn)2:
IBluetoothGattCallback中涉及的方法很多,在客戶端調(diào)用時(shí),采用了BluetoothGattCallbackWrapper模式,這樣繼承BluetoothGattCallbackWrapper的類,就不用全部把方法類出來(lái)。點(diǎn)贊
class BluetoothGattCallbackWrapper extends IBluetoothGattCallback.Stub

class AdvertiseCallbackWrapper extends BluetoothGattCallbackWrapper
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容