android蓝牙源代码分析

为了过bluetooth的PTS测试,最近研究蓝牙相关的android源代码,发现很多不错的文章,这里准备研究一下下面一些列的博客连载文章。下面链接是一系列蓝牙源码分析的连载博客。希望看完后有所帮助。

https://blog.csdn.net/shichaog/article/category/6445694/2

https://blog.csdn.net/u012439416/article/category/6475898

这里贴上第一篇内容:

安卓蓝牙应用程序编写步骤

 

1.获得BluetoothAdapter,对任何Bluetooth Activity都需要先获得。获取方法是调用getDefaultAdapter()方法。

 ​BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
    // Device does not support Bluetooth
}

getDefaultAdapter方法定义于<frameworks/base/core/java/android/bluetooth/bluetoothAdapter.java>

 ​    public static synchronized BluetoothAdapter getDefaultAdapter() {
        if (sAdapter == null) {
            IBinder b = ServiceManager.getService(BLUETOOTH_MANAGER_SERVICE);
            if (b != null) {
                IBluetoothManager managerService = IBluetoothManager.Stub.asInterface(b);
                sAdapter = new BluetoothAdapter(managerService);
            } else {
                Log.e(TAG, "Bluetooth binder is null");
            }
        }
        return sAdapter;
    }
    /**
     * Use {@link #getDefaultAdapter} to get the BluetoothAdapter instance.
     */
    BluetoothAdapter(IBluetoothManager managerService) {

        if (managerService == null) {
            throw new IllegalArgumentException("bluetooth manager service is null");
        }
        try {
            mService = managerService.registerAdapter(mManagerCallback);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        mManagerService = managerService;
        mLeScanClients = new HashMap<LeScanCallback, ScanCallback>();
        mToken = new Binder();
    }

2.使能Bluetooth

调用isEnabled()方法检查蓝牙是否已经使能。如果返回false,则说明蓝牙并未打开,调用startActivityForResult() 方法,并传递ACTION_REQUEST_ENABLE intent,这将会使蓝牙打开。

 ​if (!mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

isEnable定义于<frameworks/base/core/java/android/bluetooth/bluetoothAdapter.java>

 ​    @RequiresPermission(Manifest.permission.BLUETOOTH)
    public boolean isEnabled() {
        try {
            synchronized(mManagerCallback) {
                if (mService != null) return mService.isEnabled();
            }
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return false;
    }

startActivityForResult定义于<base/core/java/android/app/Activity.java>

 ​    public void startActivityForResult(Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode, null);
    }

这时会跳出用户许可对话框。

设备发现

使用BluetoothAdapter,不论是通过设备发现或者查询配对设备列表可以发现Bluetooth设备,设备发现是一个扫描本地蓝牙设备的过程。如果一个设备是可发现的,其将通过共享一些信息响应发现请求,这些信息如设备名,类型,MAC地址等。使用这些信息,使用这写信息,发起设备发现的设备可以和一个发现的设备进行配对。

    一旦和其它设备首次建立连接,一个配对请求自动呈现给用户。当配对完成后,设备的基本信息(设备名,类型,MAC地址)将被保存并且可以使用Bluetooth API读取。使用已知的MAC地址可以经行远程配对而不需要执行发现(假设设备在其范围)。

    配对完成和连接是有区别的,配对意味着设备双方都知道对方的存在并且有一个共享的link-key用于授权。并且双方能否建立加密连接。连接意味着设备当前共享一个RFCOMM通道并且双方能够传递数据。

当前Bluedroid API要求先配对才能建立RFCOMM通道。

   查询配对设备

在设备发现之前,查询配对设备集合是有意义的,这可以知道期望配对的设备是否已知了。这可以通过getBoundDevices()实现,其返回BluetoothDevices集合。

 ​Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
    // Loop through paired devices
    for (BluetoothDevice device : pairedDevices) {
        // Add the name and address to an array adapter to show in a ListView
        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    }
}

getBondedDevices定义于<frameworks/base/core/java/android/bluetooth/BluetoothAdapter.java>

 ​    public Set<BluetoothDevice> getBondedDevices() {
        if (getState() != STATE_ON) {
            return toDeviceSet(new BluetoothDevice[0]);
        }
        try {
            synchronized(mManagerCallback) {
                if (mService != null) return toDeviceSet(mService.getBondedDevices());
            }
            return toDeviceSet(new BluetoothDevice[0]);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return null;
    }

设备发现

调用startDiscovery()启动设备发现。该过程是异步进行的,立即返回的值表明设备发现是否启动。这一过程差不多需要12秒,然后对每一个查到的设备进行页扫以获得其Bluetooth名称。

    为了接收发现每一个设备的信息,应用程序必须为ACTION_FOUND intent注册一个BroadcastReceiver,针对每一个设备,系统将会广播ACTION_FOUND intent内容。该intent包括EXTRA_DEVICE和EXTRA_CLASS标志,分别包含了BluetoothDevice和BluetoothClass信息。

BluetoothDevice这个类定义于<frameworks/base/core/java/android/bluetooth/BluetoothDevice.java>

 ​// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // Add the name and address to an array adapter to show in a ListView
            mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    }
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

使能发现能力

如果想使设备自身能够被其它设备发现,调用startActivityForResult(Intent, int)方法,并传递ACTION_REQUEST_DISCOVERABLE intent。这将通过系统设置发出使能发现请求,缺省状态下,设备被发现的时间在120s内。但是可以通过EXTRA_DISCOVERABLE_DURATION进行修改该时长。最长可为3600s。

 ​Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);

这时将弹出一个对话框,请求用户允许设备发现,如果用户使能,则onActivityResult()回调将被调用。设备将在设定的时间内可被发现。如果想在发现模式变化时被通知,需要为ACTION_SCAN_MODE_CHANGED Intent注册BroadcastReceiver,这将包括EXTRA_SCAN_MODE和EXTRA_PREVIOUS_SCAN_MODE字段,其分别指示的是新旧扫描模式。可能的值是SCAN_MODE_CNONNECTABLE_DISCOVERABLE和SCAN_MODE_CONNECTABLE或者SCAN_MODE_NONE。

连接设备

为了将两个设备上的应用程序建立连接,必须实现server端和client端,这时因为一个设备必须打开sever socket,而另一个设备必须初始化连接(使用server设备的MAC地址初始化连接)。只有当server和client在相同的RFCOMM通道有一个已连接的BluetoothSocket。到此,每一个设备能够获得输入和输出流,数据传输可以进行了,数据传输在管理连接里叙述。此节描述如何在两个设备上初始化连接。

    server和client 设备用不同的方式获得BluetoothSocket。server端在连接建立被接受时获得,client端在为server端打开RFCOMM通道是获得。

    一个实现的技术是自动将每一个设备作为server,如此可以让每一个设备有打开并用于侦听的server socket。然后两个设备之间可以互连。

作为server连接

    当连接两个设备时,其中一个设备必须通过保持一个打开的BluetoothServerSocket作为server角色。server socket的作用是侦听接收到的连接请求,当其中一方接受时,提供一个建立连接的BluetoothScoket。当BluetoothSocket从BluetoothServerSocket获得时,除非希望接收更多的连接,否则BluetoothServerSocket应该被丢弃。

    建立server socket和接收连接的基本步骤如下:

    1.通过调用listenUsingRfcommWithServiceRecord(String, UUID)获得BluetoothServerSocket。

    String是服务的名称,系统会自动将该服务写入到服务发现协议(Service Discovery Protocol,SDP)。UUID也在SDP里并且是client连接通过的基础。

   2. 调用accept()启动连接侦听

    阻塞调用,当建立连接完成或者遇到特殊情况将会返回。只有当远端设备使用和这里的侦听socket一致的UUID发送连接请求时,这个连接才是可被接受的。当连接建立后accept()将会返回连接的BluetoothSocket()。

  3. 如果不想接收其它连接,调用close()。

    这将释放server端socket。但并不关闭由accept()返回的建立连接的BluetoothSocket。和TCP/IP不同的是,RFCOMM每个通道在一个时刻只允许一个连接的client。主activity并不适合使用阻塞的accept,通常在thread中实现。

 ​private class AcceptThread extends Thread {
    private final BluetoothServerSocket mmServerSocket;
 
    public AcceptThread() {
        // Use a temporary object that is later assigned to mmServerSocket,
        // because mmServerSocket is final
        BluetoothServerSocket tmp = null;
        try {
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
        } catch (IOException e) { }
        mmServerSocket = tmp;
    }
 
    public void run() {
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                socket = mmServerSocket.accept();
            } catch (IOException e) {
                break;
            }
            // If a connection was accepted
            if (socket != null) {
                // Do work to manage the connection (in a separate thread)
                manageConnectedSocket(socket);
                mmServerSocket.close();
                break;
            }
        }
    }
 
    /** Will cancel the listening socket, and cause the thread to finish */
    public void cancel() {
        try {
            mmServerSocket.close();
        } catch (IOException e) { }
    }
}

连接client

为了和远端的设备相连,首先应获得表示远端设备的BluetoothDevice对象,需要使用BluetoothDevice 接收BluetoothSocket 并且初始化连接。

主要过程如下:

    1.使用BluetoothDevice,通过调用createRfcommSocketToServiceRecord(UUID)获得BluetoothSocket

    这初始化了将连接到BluetoothDevice的BluetoothSocket。这里传递的UUID必须和server端设备使用的保持一致,使用一样的UUID是硬编码UUID到应用程序。

    2.使用connect()初始化连接

    该调用会引起系统执行远端设备SDP查找以匹配UUID。如果成功查找并且远端设备接受连接,connect()将会返回,在连接时RFCOMM通道将共享。

 ​private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;
 
    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;
 
        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }
 
    public void run() {
        // Cancel discovery because it will slow down the connection
        mBluetoothAdapter.cancelDiscovery();
 
        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }
 
        // Do work to manage the connection (in a separate thread)
        manageConnectedSocket(mmSocket);
    }
 
    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

连接管理

当多个设备成功建立连接时,每一个设备都有一个连接的BluetoothSocket。通过其可以让设备间共享数据。使用BluetoothSocket,传递任意数据的过程是比较简单的。

1.使用getInputStream()和getOutputStream()分别获得InputStream和OutputStream的socket传输句柄。

2.使用read(byte[])和write(byte[])向stream中写入数据

使用应该使用专用的thread服务与所有的stream reading和writing。

 ​private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;
 
    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
 
        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }
 
        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }
 
    public void run() {
        byte[] buffer = new byte[1024];  // buffer store for the stream
        int bytes; // bytes returned from read()
 
        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }
 
    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }
 
    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

如何使用profile

profile是两个设备基于蓝牙通信的无线接口规范。一个例子是Hands-Free profile。对于手机连接到无线耳机情景,两个设备必须都支持Hands-Free profile。

可以使用BluetoothProfile创建一个特殊自有的profile。安卓蓝牙API支持以下Bluetooth profile。

Headset。耳机和手机见的profile,BluetoothHeadset类,

A2DP, BluetoothA2dp

Health Device。

使用profile的基本步骤如下

1.获得默认的adapter

2.使用getProfileProxy()建立profile代理对象和profile之间的连接

3.建立BluetoothProfile.ServerListener。

4.在onServiceConnected(),获得profile代理对象的句柄。

5.一旦获得profile代理,可以使用其检测连接状态,或者执行profile能够提供的功能。

 ​BluetoothHeadset mBluetoothHeadset;
 
// Get the default adapter
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
 
// Establish connection to the proxy.
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET);
 
private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
    public void onServiceConnected(int profile, BluetoothProfile proxy) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = (BluetoothHeadset) proxy;
        }
    }
    public void onServiceDisconnected(int profile) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null;
        }
    }
};
 
// ... call functions on mBluetoothHeadset
 
// Close proxy connection after use.
mBluetoothAdapter.closeProfileProxy(mBluetoothHeadset);
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值