Android蓝牙

来源:互联网 发布:侠盗飞车for mac 编辑:程序博客网 时间:2024/05/31 06:22

Android平台支持蓝牙网络栈协议Bluetooth network stack,允许蓝牙设备之间交换数据。通过Bluetooth API,framework层提供访问蓝牙的功能。能够让蓝牙设备之间点到点连接或者多点连接。

Android应用可以做的:扫描其他蓝牙设备;配对的蓝牙设备间询问蓝牙适配器;建立RFCOMM 通道;通过服务发现连接其他设备;在设备间传输数据;管理多连接;

       使用Classic Bluetooth,主要是电池敏感的设备上是不错的选择。Android从4.3(API 18)开始支持Bluetooth Low Energy(BLE)。

        Android Bluetooth通讯需要完成4个主要步骤任务,开启蓝牙setting up Bluetooth、find devices局域范围发现设备,connecting devices连接设备,transfering data设备间传输数据。

蓝牙API包是android.bluetooth,下面是几个主要的类和接口:

BluetoothAdapter:蓝牙适配器是所有蓝牙交互的入口。通过这个类能发现其他蓝牙设备,查询绑定的蓝牙设备,用MAC地址初始化一个蓝牙设备,创建BluetoothServerSocket监听蓝牙设备的连接。

BluetoothDevice:代表一个远端蓝牙设备,使用它通过BluetoothSocket发起一个到远端设备的连接或者查询设备的名字、地址、类名和配对状态等信息。

  BluetoothSocket:类似TCP的Socket的Bluetooth socket,通过inputStream和outputStream允许应用与其他蓝牙设备交换数据的连接点。

BluetoothServerSocket::代表Server端socket用来监听请求,为了使两个android设备连接起来,一个设备必须open这个server socket。当远端设备发送一个连接请求到该设备,BluetoothServerSocket接受连接请求后会返回一个BluetoothSocket。

BluetoothClass:描述蓝牙设备的一般特性和功能。

BluetoothProfile:蓝牙的profile文件。

BluetoothHeadset:蓝牙耳机。

BluetoothA2dp:定义了一个设备到另一个设备的高质量音频传输流

BluetoothHealth:控制蓝牙服务的设备描述文件的代理。

BluetoothHealthCallback:需要实现BluetoothHealth callback的抽象类。实现更新应用的注册状态和蓝牙channel状态。

BluetoothHealthAppConfiguration:应用配置

        BluetoothProfile.ServiceListener:通知BluetoothProfile IPC client,连接或者断开。

Bluetooth Permissions

<manifest ... >  <uses-permission android:name="android.permission.BLUETOOTH" />  ...</manifest>
Setting up Bluetooth:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();if (mBluetoothAdapter == null) {    // Device does not support Bluetooth}
if (!mBluetoothAdapter.isEnabled()) {    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);}
   onActivityResult()  RESULT_OK RESULT_CANCELED   
还可以监听广播 ACTION_STATE_CHANGED。


Finding Devices
发现,蓝牙设备会回复一个发现请求信息,包括name class MAC。通过这些信息设备才可以建立连接。

配对请求发送给蓝牙设备,配对成功以后name class MAC信息都会被保存起来。通过已知的MAC地址,连接可以在任何时候初始化不必执行discovery。
配对和连接是不同的,配对是两个设备意识到设备之间的存在,有一个共享的link-key用作认证并且可以建立加密的连接。连接意味着设备共享一个RFCOMM channel并且可以传输数据。必须先配对再连接。(当你执行一个加密连接的初始化配对会自动的执行)。
查询配对设备:
   
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();// If there are paired devicesif (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());    }}
startDiscovery()12秒中的扫描时间,需要注册一个广播Action_found
// Create a BroadcastReceiver for ACTION_FOUNDprivate 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 BroadcastReceiverIntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

执行设备发现是一个比较中的程序,需要消耗需要资源。而且如果你的设备已经连接了一个蓝牙设备后,如果再执行startDiscovery()那么带宽将受到减小的影响。当然可以使用cancelDiscovery()来取消发现操作。

可以设置发现蓝牙设备的时间,最长可以为3600s,如果设置成0则设备将总是处在发现。默认是120s。

Intent discoverableIntent = newIntent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 100);startActivity(discoverableIntent);

有个dialog提示用户允许蓝牙设备发现,如果用户同意,那之后就会执行蓝牙发现,再之后就会回调Activity的onActivityResult();如果用户不同意或者错误发生了,则会回调RESULT_CANCELED的resultcode。

如果蓝牙设备没有开启,那么enable设备发现则会自动开启。

之后蓝牙就一直处于发现模式,你可以注册Action_scan_mode_changed的BroadcastReceiver,

SCAN_MODE_CONNECTABLE_DISCOVERABLE、SCAN_MODE_CONNECTABLE,或SCAN_MODE_NONE分别是发现模式、不在发现模式但仍然可以接受链接、不在发现模式也不能接受链接。

2.连接设备

通过你的应用产生一个蓝牙设备连接,必须实现CS机制,一个设备打开server socket而另一个设备要初始化连接。

server端和client端每一端通过不同的方式获取BluetoothSocket。

不想TCP/IP,RFCOMM一个channel只允许一个连接。accept不能在UI线程上执行

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) { }    }}


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) { }    }}

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) { }    }}
BluetoothHeadset mBluetoothHeadset; // Get the default adapterBluetoothAdapter 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);

更系统点介绍如下:(以下部分转载自http://blog.csdn.net/gd920129/article/details/7487761

1. 使用蓝牙的相应权限

?
1
2
<strong>    <uses-permissionandroid:name="android.permission.BLUETOOTH"/> 
    <uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN"/>  </strong>


2. 配置本机蓝牙模块

在这里首先要了解对蓝牙操作一个核心类BluetoothAdapter

?
1
2
3
4
5
6
7
8
9
10
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); 
//直接打开系统的蓝牙设置面板 
Intent intent = newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
startActivityForResult(intent, 0x1); 
//直接打开蓝牙 
adapter.enable(); 
//关闭蓝牙 
adapter.disable(); 
//打开本机的蓝牙发现功能(默认打开120秒,可以将时间最多延长至300秒) 
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//设置持续时间(最多300秒)Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

3.搜索蓝牙设备

使用BluetoothAdapter的startDiscovery()方法来搜索蓝牙设备

startDiscovery()方法是一个异步方法,调用后会立即返回。该方法会进行对其他蓝牙设备的搜索,该过程会持续12秒。该方法调用后,搜索过程实际上是在一个System Service中进行的,所以可以调用cancelDiscovery()方法来停止搜索(该方法可以在未执行discovery请求时调用)。

请求Discovery后,系统开始搜索蓝牙设备,在这个过程中,系统会发送以下三个广播:

ACTION_DISCOVERY_START:开始搜索

ACTION_DISCOVERY_FINISHED:搜索结束

ACTION_FOUND:找到设备,这个Intent中包含两个extra fields:EXTRA_DEVICE和EXTRA_CLASS,分别包含BluetooDevice和BluetoothClass。

我们可以自己注册相应的BroadcastReceiver来接收响应的广播,以便实现某些功能

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 创建一个接收ACTION_FOUND广播的BroadcastReceiver 
privatefinal BroadcastReceiver mReceiver = newBroadcastReceiver() { 
    publicvoid onReceive(Context context, Intent intent) { 
        String action = intent.getAction(); 
        // 发现设备 
        if(BluetoothDevice.ACTION_FOUND.equals(action)) { 
            // 从Intent中获取设备对象 
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
            // 将设备名称和地址放入array adapter,以便在ListView中显示 
            mArrayAdapter.add(device.getName() + "\n"+ device.getAddress()); 
        
    
}; 
// 注册BroadcastReceiver 
IntentFilter filter = newIntentFilter(BluetoothDevice.ACTION_FOUND); 
registerReceiver(mReceiver, filter); // 不要忘了之后解除绑定

4. 蓝牙Socket通信

如果打算建议两个蓝牙设备之间的连接,则必须实现服务器端与客户端的机制。当两个设备在同一个RFCOMM channel下分别拥有一个连接的BluetoothSocket,这两个设备才可以说是建立了连接。

服务器设备与客户端设备获取BluetoothSocket的途径是不同的。服务器设备是通过accepted一个incoming connection来获取的,而客户端设备则是通过打开一个到服务器的RFCOMM channel来获取的。

 

服务器端的实现

通过调用BluetoothAdapter的listenUsingRfcommWithServiceRecord(String, UUID)方法来获取BluetoothServerSocket(UUID用于客户端与服务器端之间的配对)

调用BluetoothServerSocket的accept()方法监听连接请求,如果收到请求,则返回一个BluetoothSocket实例(此方法为block方法,应置于新线程中)

如果不想在accept其他的连接,则调用BluetoothServerSocket的close()方法释放资源(调用该方法后,之前获得的BluetoothSocket实例并没有close。但由于RFCOMM一个时刻只允许在一条channel中有一个连接,则一般在accept一个连接后,便close掉BluetoothServerSocket

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
privateclass AcceptThread extendsThread {
    privatefinal BluetoothServerSocket mmServerSocket;
 
    publicAcceptThread() {
        // 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;
    }
 
    publicvoid 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 */
    publicvoid cancel() {
        try{
            mmServerSocket.close();
        catch(IOException e) { }
    }
}
客户端的实现

通过搜索得到服务器端的BluetoothService

调用BluetoothService的listenUsingRfcommWithServiceRecord(String, UUID)方法获取BluetoothSocket(该UUID应该同于服务器端的UUID)

调用BluetoothSocket的connect()方法(该方法为block方法),如果UUID同服务器端的UUID匹配,并且连接被服务器端accept,则connect()方法返回

注意:在调用connect()方法之前,应当确定当前没有搜索设备,否则连接会变得非常慢并且容易失败

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<strong>    privateclass ConnectThread extendsThread { 
        privatefinal BluetoothSocket mmSocket; 
        privatefinal BluetoothDevice mmDevice; 
       
        publicConnectThread(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; 
        
       
        publicvoid 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 */ 
        publicvoid cancel() { 
            try
                mmSocket.close(); 
            catch(IOException e) { } 
        
    }  </strong>
连接管理(数据通信)

分别通过BluetoothSocket的getInputStream()和getOutputStream()方法获取InputStream和OutputStream

使用read(bytes[])和write(bytes[])方法分别进行读写操作

注意:read(bytes[])方法会一直block,知道从流中读取到信息,而write(bytes[])方法并不是经常的block(比如在另一设备没有及时read或者中间缓冲区已满的情况下,write方法会block)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<strong>    privateclass ConnectedThread extendsThread { 
        privatefinal BluetoothSocket mmSocket; 
        privatefinal InputStream mmInStream; 
        privatefinal OutputStream mmOutStream; 
       
        publicConnectedThread(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; 
        
       
        publicvoid run() { 
            byte[] buffer = newbyte[1024];  // buffer store for the stream 
            intbytes; // 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 */ 
        publicvoid cancel() { 
            try
                mmSocket.close(); 
            catch(IOException e) { } 
        
    }  </strong>

0 0