Android之Bluetooth通信-经典蓝牙通信BluetoothSocket

简介

通过蓝牙传输文件,其实现流程是怎样的?这里从JAVA/JNI/HAL三个角度分析
注:
服务端为BluetoothServerSocket

以BluetoothSocket创建为案例 -- 7.1代码

JAVA -- Bluetooth.apk

packages/apps/Bluetooth
frameworks/base/core/java/android/bluetooth

1.关键方法

BluetoothOppTransfer.java

BluetoothSocket btSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);

btSocket.connect();

2.分析

1.bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);

BluetoothDevice.java
    public BluetoothSocket createInsecureRfcommSocketToServiceRecord(UUID uuid) throws IOException {
        if (isBluetoothEnabled() == false) {
            Log.e(TAG, "Bluetooth is not enabled");
            throw new IOException();
        }
        return new BluetoothSocket(BluetoothSocket.TYPE_RFCOMM, -1, false, false, this, -1,
                new ParcelUuid(uuid));//创建BluetoothSocket对象
    }
    
2.btSocket.connect();

BluetoothSocket.java
   public void connect() throws IOException {
        if (mDevice == null) throw new IOException("Connect is called on null device");

        try {
            if (mSocketState == SocketState.CLOSED) throw new IOException("socket closed");
            IBluetooth bluetoothProxy =
                    BluetoothAdapter.getDefaultAdapter().getBluetoothService(null);
            if (bluetoothProxy == null) throw new IOException("Bluetooth is off");
            mPfd = bluetoothProxy.connectSocket(mDevice, mType,
                    mUuid, mPort, getSecurityFlags());//获取ParcelFileDescriptor,即FileDescriptor的Android包装类
            synchronized(this)
            {
                if (DBG) Log.d(TAG, "connect(), SocketState: " + mSocketState + ", mPfd: " + mPfd);
                if (mSocketState == SocketState.CLOSED) throw new IOException("socket closed");
                if (mPfd == null) throw new IOException("bt socket connect failed");
                FileDescriptor fd = mPfd.getFileDescriptor();//把ParcelFileDescriptor转化为fd
                mSocket = new LocalSocket(fd);//建立Socket连接准备
                mSocketIS = mSocket.getInputStream();
                mSocketOS = mSocket.getOutputStream();
            }
            int channel = readInt(mSocketIS);
            if (channel <= 0)
                throw new IOException("bt socket connect failed");
            mPort = channel;
            waitSocketSignal(mSocketIS);//等待连接。这里代表connect是堵塞的方法
            synchronized(this)
            {
                if (mSocketState == SocketState.CLOSED)
                    throw new IOException("bt socket closed");
                mSocketState = SocketState.CONNECTED;
            }
        } catch (RemoteException e) {
            Log.e(TAG, Log.getStackTraceString(new Throwable()));
            throw new IOException("unable to send RPC: " + e.getMessage());
        }
    }
    
3.接下来我们先分析怎么等待连接,其后再重点讲解mPfd的来源
waitSocketSignal(mSocketIS)

    private String waitSocketSignal(InputStream is) throws IOException {
        byte [] sig = new byte[SOCK_SIGNAL_SIZE];
        int ret = readAll(is, sig);//等待连接的关键方法
        ······
        return RemoteAddr;
    }
    
    private int readAll(InputStream is, byte[] b) throws IOException {
        int left = b.length;
        while(left > 0) {
            int ret = is.read(b, b.length - left, left);//inputstream.read就会阻塞,此方法为常见方法
            if(ret <= 0)
                 throw new IOException("read failed, socket might closed or timeout, read ret: "
                         + ret);
            left -= ret;
            if(left != 0)
                Log.w(TAG, "readAll() looping, read partial size: " + (b.length - left) +
                            ", expect size: " + b.length);
        }
        return b.length;
    }
    
4.现在重点讲解mPfd的来源
IBluetooth bluetoothProxy =
                    BluetoothAdapter.getDefaultAdapter().getBluetoothService(null);
mPfd = bluetoothProxy.connectSocket(mDevice, mType,
                    mUuid, mPort, getSecurityFlags());
                    
bluetoothProxy代理的Binder对象,其实就是AdapterService

AdapterService.java

     ParcelFileDescriptor connectSocket(BluetoothDevice device, int type,
                                              ParcelUuid uuid, int port, int flag) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
        int fd = connectSocketNative(Utils.getBytesFromAddress(device.getAddress()),
                   type, Utils.uuidToByteArray(uuid), port, flag, Binder.getCallingUid());//通过jni获取fd
        if (fd < 0) {
            errorLog("Failed to connect socket");
            return null;
        }
        return ParcelFileDescriptor.adoptFd(fd);//通过fd创建ParcelFileDescriptor
    }
来到connectSocketNative代表来到了JNI层,下面我们重点简介JNI层

JNI -- libbluetooth_jni.so (/system/lib/libbluetooth_jni.so)

packages\apps\Bluetooth\jni

jni分析

com_android_bluetooth_btservice_AdapterService.cpp
static int connectSocketNative(JNIEnv *env, jobject object, jbyteArray address, jint type,
                                   jbyteArray uuidObj, jint channel, jint flag, jint callingUid) {
    ···
    if ( (status = sBluetoothSocketInterface->connect((bt_bdaddr_t *) addr, (btsock_type_t) type,
                       (const uint8_t*) uuid, channel, &socket_fd, flag, callingUid))
            != BT_STATUS_SUCCESS) {
        ALOGE("Socket connection failed: %d", status);
        goto Fail;
    }
    ···
    return socket_fd;//sBluetoothSocketInterface->connect函数将socket_fd传进去并被赋值

Fail:
    if (addr) env->ReleaseByteArrayElements(address, addr, 0);
    if (uuid) env->ReleaseByteArrayElements(uuidObj, uuid, 0);

    return -1;
}


这里sBluetoothSocketInterface->connect其实就是进入了HAL层

HAL层 --- bluetooth.default.so

system\bt

1.在分析HAL层代码之前,我们先搞清楚jni怎么关联上HAL成的

讲解sBluetoothSocketInterface->connect之前,我们先了解一下sBluetoothSocketInterface的由来

1.在jni的initNative初始化
static bool initNative(JNIEnv* env, jobject obj) {
    ALOGV("%s:",__FUNCTION__);
    ···
    if ( (sBluetoothSocketInterface = (btsock_interface_t *)
                  sBluetoothInterface->get_profile_interface(BT_PROFILE_SOCKETS_ID)) == NULL) {
                ALOGE("Error getting socket interface");
        }
    ···
    return JNI_FALSE;
}
要弄清楚sBluetoothSocketInterface,则一定要弄清楚sBluetoothInterface

2.在jni的classInitNative初始化
static void classInitNative(JNIEnv* env, jclass clazz) {
    int err;
    hw_module_t* module;
    ····
    if (!strncmp(type, "RTL", 3)) {
        ALOGD("%s, load %s.default.so", __func__, BT_STACK_RTK_MODULE_ID);
        err = hw_get_module(BT_STACK_RTK_MODULE_ID, (hw_module_t const**)&module);
    } else {
        ALOGD("%s, load %s.default.so", __func__, id);
        err = hw_get_module(id, (hw_module_t const**)&module);
    }

    if (err == 0) {
        hw_device_t* abstraction;
        err = module->methods->open(module, id, &abstraction);//关键点1
        if (err == 0) {
            bluetooth_module_t* btStack = (bluetooth_module_t *)abstraction;
            sBluetoothInterface = btStack->get_bluetooth_interface();//通过btStack获取
        } else {
           ALOGE("Error while opening Bluetooth library");
        }
    } else {
        ALOGE("No Bluetooth Library found");
    }
}
想要弄清楚sBluetoothInterface的来路,则一定要弄清楚btStack的来源

2.真正HAL层代码来了。btStack的来源就是Android标准的JNI到HAL层架构方式

注意:
blutooth.default.so的源码来自system/bt

1)查看bluetooth.c
static int open_bluetooth_stack(const struct hw_module_t *module, UNUSED_ATTR char const *name, struct hw_device_t **abstraction) {
  static bluetooth_device_t device = {
    .common = {
      .tag = HARDWARE_DEVICE_TAG,
      .version = 0,
      .close = close_bluetooth_stack,
    },
    .get_bluetooth_interface = bluetooth__get_bluetooth_interface
  };

  device.common.module = (struct hw_module_t *)module;
  *abstraction = (struct hw_device_t *)&device;//abstraction就是btStack
  return 0;
}

static struct hw_module_methods_t bt_stack_module_methods = {
    .open = open_bluetooth_stack,//关键点1的真实调用方法open_bluetooth_stack
};

a)btStack调用get_bluetooth_interface,其实调用的是bluetooth__get_bluetooth_interface

b)bluetoothInterface的来源
const bt_interface_t* bluetooth__get_bluetooth_interface ()
{
    /* fixme -- add property to disable bt interface ? */

    return &bluetoothInterface;
}

bluetoothInterface的结构体bt_interface_t

c)查看bt_interface_t
static const bt_interface_t bluetoothInterface = {
    ···
    get_profile_interface,
    ···
};

3.至此已经解锁sBluetoothInterface的来源,反推sBluetoothSocketInterface的来源

sBluetoothSocketInterface = (btsock_interface_t *)
                  sBluetoothInterface->get_profile_interface(BT_PROFILE_SOCKETS_ID)
static const void* get_profile_interface (const char *profile_id)
{
    ···
    if (is_profile(profile_id, BT_PROFILE_SOCKETS_ID))
        return btif_sock_get_interface();
    ···
    return NULL;
}

btif_sock.c
btsock_interface_t *btif_sock_get_interface(void) {
  static btsock_interface_t interface = {
    sizeof(interface),
    btsock_listen,
    btsock_connect
  };
  return &interface;
}

bt_sock.h
typedef struct {
    /** set to size of this struct*/
    size_t          size;

    bt_status_t (*listen)(btsock_type_t type, const char* service_name,
            const uint8_t* service_uuid, int channel, int* sock_fd, int flags, int callingUid);

    bt_status_t (*connect)(const bt_bdaddr_t *bd_addr, btsock_type_t type, const uint8_t* uuid,
            int channel, int* sock_fd, int flags, int callingUid);
} btsock_interface_t

connect 对应到 btsock_connect

4.至此已经来到HAL层的connect处

btif_sock.c

static bt_status_t btsock_connect(const bt_bdaddr_t *bd_addr, btsock_type_t type, const uint8_t *uuid, int channel, int *sock_fd, int flags, int app_uid) {
  ···
  bt_status_t status = BT_STATUS_FAIL;

  switch (type) {
    case BTSOCK_RFCOMM://选择此通道
      status = btsock_rfc_connect(bd_addr, uuid, channel, sock_fd, flags, app_uid);
      break;
    ···
  }
  return status;
}


bt_status_t btsock_rfc_connect(const bt_bdaddr_t *bd_addr, const uint8_t *service_uuid, int channel, int *sock_fd, int flags, int app_uid) {
  ···
  *sock_fd = slot->app_fd;    // Transfer ownership of fd to caller.
  slot->app_fd = INVALID_FD;  // Drop our reference to the fd.
  slot->app_uid = app_uid;
  btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id);//发数据发送出去
  status = BT_STATUS_SUCCESS;

out:;
  pthread_mutex_unlock(&slot_lock);
  return status;
}


btif_sock_thread.c 发送数据
int btsock_thread_add_fd(int h, int fd, int type, int flags, uint32_t user_id)
{
    ···
    OSI_NO_INTR(ret = send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0));//socket发送数据

    return ret == sizeof(cmd);
}

总结

1.apk -- jni -- hal 整个过程有很多Android定制的代码实现的框架格式
2.弄清楚基础的框架格式,再分析源码的流程就方便很多
3.跨设备,其实通信用的就是socket

demo案例

1.development\samples\BluetoothChat
2.https://github.com/googlearchive/android-BluetoothChat#readme
3.https://blog.csdn.net/mo_android/article/details/76472824
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 175,490评论 5 419
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 74,060评论 2 335
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 124,407评论 0 291
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 47,741评论 0 248
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 56,543评论 3 329
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 43,040评论 1 246
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 34,107评论 3 358
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 32,646评论 0 229
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 36,694评论 1 271
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 32,398评论 2 279
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 33,987评论 1 288
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 30,097评论 3 285
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 35,298评论 3 282
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 27,278评论 0 14
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 28,413评论 1 232
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 38,397评论 2 309
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 38,099评论 2 314

推荐阅读更多精彩内容