Android Bluetooth development (1)

statement

Ordinary Bluetooth devices official documents

Android platform includes Bluetooth network stack supports , by virtue of this support, the device can exchange data with other Bluetooth devices wirelessly. Application Framework provides a way through the Android Bluetooth API access Bluetooth-enabled. Using the Bluetooth API Android application may perform the following operations:

  • Scan for other Bluetooth devices
  • Queries paired Bluetooth devices local Bluetooth adapter
  • Establish RFCOMM channel
  • Connecting to other devices through a service discovery
  • Bi-directional data transfer with other devices
  • Managing multiple connections

Traditional use Bluetooth for battery operation greater strength, for example, and the communication between the streaming Android equipment. For Bluetooth devices with low power requirements, Android 4.3 in (18 is API) for the introduction of a low-power Bluetooth API support.

Basics

Use Android Bluetooth API accomplished using Bluetooth communication four main tasks: setting Bluetooth , find the pairing devices in a local area or available device, connected to the device , and the transmission of data between devices .

About Bluetooth API in the android.bluetoothpackage, below introduce the main classes and Bluetooth related

BluetoothAdapter

Local Bluetooth adapter, all entry points interact with Bluetooth , the Bluetooth device itself represents a Bluetooth adapter, the whole system has only one Bluetooth adapter . It can be found by other Bluetooth devices, query list binding (pairing) devices, using a known Mac address instantiation BluetoothDeviceand creation BluetoothServerSocketto listen for communications from other devices.

BluetoothDevice

It represents the remote Bluetooth device. It can use BluetoothSocketto establish a connection with a remote device a request or query information about the device, such as device name, address, type, and binding status.

BluetoothSocket

Indicates that Bluetooth socket interface (similar to TCP Socket). This is permitted by the application InputStreamand the OutputStreamnode with other Bluetooth devices to exchange data. It is using this target to complete the data exchange between Bluetooth devices,

BluetoothServerSocket

Denotes a development server socket listening for incoming requests (like TCP ServerSocket) connecting two Android device, wherein a device can not be developed using such a server socket. When a remote Bluetooth device a connection request to the device, BluetoothServerSocketwill return after receiving connector connected BluethoothSocket.

BluetoothClass

General description Bluetooth device features and functions. This read-only attribute is set, the primary and secondary device class is used to define the device and its services. However, it can not reliably describe the device supports all Bluetooth profiles and services, but as a device suitable for the type of prompt.

BluetoothProfile

It denotes an interface Bluetooth profile. Bluetooth profiles are applied to the device between the Bluetooth wireless communications interface specification . Hands-free profile is an example. For a detailed discussion of the configuration file, refer to the following configuration file to explain

BluetoothHeadset

Provide support for Bluetooth headset, for use with mobile phones. Including Bluetooth headsets and hands-free (version 1.5) profile. BluetoothProfile implementation class

BlutoothA2dp
defined quality audio how a Bluetooth connection and streaming, transferred from one device to another device. "A2DP" represents the advanced audio distribution profile. It is BluetoothProfile implementation class

BluetoothHealth
represents health services for controlling the Bluetooth device configuration file agents. BluetoothProfile implementation class.

BluetoothGatt

BluetoothProfile implementation class . Low-power Bluetooth communication related to the proxy configuration file

BluetoothHealthCallback
used to implement an abstract class BluetoothHealth callback. We must extend and implement such a callback method to receive updates on the application of the registration status and Bluetooth channel status change content.
BluetoothHealthAppConfiguration
represents health applications Bluetooth Configuration third party registration so as to communicate with a remote BLUETOOTH device health
BluetoothProfile.ServiceListener
connected BluetoothProfile IPC client to the service (i.e., run specific internal profile service) or disconnected send a service connection Interface notice.

Bluetooth permission

Bluetooth permission must be declared BLUETOOTH can perform Bluetooth communication.

 <mainifest>
    <uses-permission android:name = "android.permission.BLUETOOTH"/>
    <!--启用应用启动设备发现或者操作蓝牙设备的超级管理员-->
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
</mainifest>

Bluetooth settings

  1. Get a Bluetooth adapter
    to all Bluetooth BluetoothAdapter of Activity are required. To get a static method call BluetoothAdapter BluetoothAdapter the getDefaultAdapter()method. BluetoothAdapter device itself will return a Bluetooth adapter (Bluetooth device) FIG.
    The entire system has a Bluetooth adapter, we can interact with the application by BluetoothAdapter this object. If you getDefaultAdapter()return null it indicates that the device does not support Bluetooth .
    
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if(mBluetoothAdapter == null){
        // 说明此设备不支持蓝牙操作
    }
  1. Enable Bluetooth
    must make sure Bluetooth is turned on isEnabled(). Return false it indicates that Bluetooth is turned off. Request to enable Bluetooth. Use ACTION_REQUEST_ENABLEoperating Intent calls startActivityForResult()to request a Bluetooth-enabled through system settings. It can also mBluetoothAdapter.enable()directly open the Bluetooth.
   // 没有开始蓝牙
   if(!mBluetoothAdapter.isEnabled()){
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent,REQUEST_ENBLE_BT);
   }

Our application can also choose to listen for ACTION_STATE_CHANGEDbroadcast Intent. Whenever Bluetooth status changes, the system will broadcast the Intent. This broadcast contains additional fields EXTRA_STATEand EXTRA_PREVIOUS_STATErepresent the new and old Bluetooth status.

Find Device

Use BluetoothAdapter can be found or to find remote Bluetooth devices paired devices list query through the device.
Device discovery is a scanning process, it searches for Bluetooth-enabled devices within a local area and request some information about each device. This process is also known as discovery, inquiry scan. Bluetooth devices within a local area only when it is enabled detectable current will respond to discovery requests . If the device can be detected, it responds by sharing some of the information (e.g., device name, class and its unique MAC address) discovery request. Using this information, the device performs discovery may be selected to initiate a connection device is found.

After the first connection to a remote device, it will automatically display a pairing request to the user. After the completion of the pairing device will save the basic information about the device (such as device name, MAC address). And using the Bluetooth API can read the information. Using the Mac address of the remote device is known to keep it can initiate a connection, without performing discovery operation (assuming that the device is within range).

It is paired and there is a difference between the connection . Means that two devices are paired with each other in its presence, they can have a shared link key for authentication, and to establish an encrypted connection with each other. It means that the device is connected a current share RFCOMM channel, and can transmit data to each other. The current Android Bluetooth API requirements for device pairing before you can establish a RFCOMM connection (when using the Bluetooth API to initiate an encrypted connection will automatically perform pairing). Android device is undetectable in the default state.

Query paired device

Before performing the discovery, it is necessary to query a collection of paired device. To understand whether the device is in a known state. By getBondedDevices()achieved, it will returns a set of paired devices BluetoothDevice.

For example: we can query all paired devices, and then use ArrayAdapter displays the name of each device to the user:

    
    Set<BluetoothDevice> pairedDevices = mBlutooothAdapter.getBondedDevices();
    
    if(pairedDevices.size() > 0){
        for(BluetoothDevice device:pairedDevices){
            // 把名字和地址取出来添加到适配器中
            mArrayAdapter.add(device.getName()+"\n"+ device.getAddress());
        }
    }

To initiate a connection only needs to know the Mac address of the target Bluetooth device on it.

Discovery

Discover devices using startDiscovery()the process as an asynchronous process. This method will immediately return a Boolean value that indicates whether the operation has been started successfully found. The discovery process usually contains a query scans about 12 seconds, after which the device was found to be scanned to retrieve the name of the Bluetooth device.

We must apply for ACTION_FOUNDregistration a BroadcastReceiver Intent, in order to receive information for each discovered device. For each device, the system will broadcast ACTION_FOUND Intent. This Intent carries the extra fields EXTRA_DEVICE and EXTRA_CLASS. Both contain the BluetoothDevice and BluetoothClass.

   // 创建一个接受 ACTION_FOUND 的 BroadcastReceiver
   private final BroadcastReceiver mReceiver = new BroadcastReceiver(){
   
        public void onReceive(Context context,Intent intent){
            String action = intent.getAction();
            // 当 Discovery 发现了一个设备  
            if(BluetoothDevice.ACTION_FOUND.equals(action)){
                // 从 Intent 中获取发现的 BluetoothDevice 
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 将名字和地址放入要显示的适配器中
                mArrayAdapter.add(device.getName + "\n" + device.getAddress());
                
            }
        }
   };
   // 注册这个 BroadcastReceiver
   IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
   registerReceiver(mReiver,filter);
   
   // 在 onDestroy 中 unRegister

Note that the implementation of discovery for the Bluetooth adapter is a very arduous process, and will consume a lot of resources. After finding the device you want to connect, be sure to use cancelDiscovery()to stop the discovery, and then try to connect . If you have a device to connect and then execute a discovery this time will greatly reduce the available bandwidth for this connection! So when it should not be in a connected state execute a discovery!

Enable detectability

If we want our devices can be detected by other devices can be used ACTION_REQUEST_DISCOVERABLEto operate the Intent call startActivityForResult(Intent,int). This will enable the issue to be detected mode of request (no need to stop our application) by system settings. By default, the device becomes a detectable state and for 120 seconds. We can also EXTRA_DISCOVERABLE_DURATIONIntent Extra
to define different durations. The maximum duration can be set for 3600 seconds. Value 0 indicates always be detected . Any value less than 0 or greater than the value of 3600 will be automatically set to 120 seconds.

E.g:

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

The dialog box is displayed, requesting the user to allow the device to be detected. If the user response is YES, the amount of time the device will become continuously detected and specified. Activity then you will receive a callback call to onActivityResult (), the result code is equal to the device can detect the duration. If NO in response to user error or a result code RESULT_CANCELED

If the device does not turn on Bluetooth-enabled devices can detect the sex of time it will automatically enable Bluetooth.

The holding device in silent mode can be detected within the allotted time mode. If we want to be notified when a detectable change mode, you can take advantage of ACTION_SCAN_MODE_CHANGEDIntent registered BroadcastReceiver. It will include additional fields EXTRA_SCAN_MODE and EXTRA_PREVIOUS_SCAN_MODE, respectively, both new and old tell us the scan mode. Each field may include SCAN_MODE_CONNECTABLE_DISCOVERABLE (detectable mode), SCAN_MODE_CONNECTABLE (not detectable in the connection mode but acceptable), SCAN_MODE_NOE (not in the detected pattern and can not be connected)

Connected devices

To create a connection between the two devices on the application, you must implement server and client mechanism, because one device must open a server socket, and the other equipment must initiate the connection (using the server device's MAC address initiates the connection). When the server and the client, respectively, have BluetoothSocket connected on the same RFCOMM channel, both of which will be considered connected to each other. In this case, each device have access to the input and output stream, and may begin transmitting data.

Service and client are different ways to get BluetoothSocket. The server will receive socket when an incoming connection is accepted. The client will receive the socket at its open RFCOMM channel to the server.

One implementation is to automatically prepare a server for each device, so that the development of each device connected to a server socket and listens. Then either device can initiate a connection with another device, and become the client. Or in which one device may display "managed" server connection and a socket open on demand, thereby initiating another device directly connected.

If two devices are not paired, the system will automatically send the connection request before pairing

Connections for servers

When connecting two devices, one of which must be maintained developed BluetoothServerSocketto act as a server, listens for incoming connection requests, already provide a connection after receiving the request BluetoothSocket. From BluetoothServerSocketconnections to obtain BluetoothSocketafter you can call the close to close the wait.

About UUID

Universally unique identifier (the UUID), a string representing the unique identification information ID, 128. With numerous randomly generated UUID on the network, and then formString(String)to initialize a UUID.

The basic process server socket to accept connections

  • by listenUsingRfcommWithServiceRecord(String,UUID)获取 BluetoothServerSocket

    String name of the service is to identify our own definition, you can use the package name directly. The system will be custom written to a new service on the database entry device discovery protocol (SDP) in. UUID also the SDP, as a client device connected to the protocol matching rules. Only the client and the UUID here as it can be connected

  • accept() Listen for connection requests

    Blocking calls will be returned when the connection is accepted or exception occurs, the operation is successful, it will return BluetoothSocket.

  • Unless you want to accept more connections, or the call close()to close this listener

    This will release the server socket and all its resources, but does not close BluetoothSocket already connected. And TCP / IP is different, RFCOMM only allows each channel has a client already connected.

In sub-thread execution.

example:

private class AcceptThread extend Thread{
    private final BluetoothServerSocket mServerSocket;
    public AcceptThread(){
        mServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME,MY_UUID);
    }
    
    public void run(){
        BluetoothSocket socket = null;
        while(true){
            socket = mServerSocket.accept();
            if(socket!=null){
                // 自定义方法
                manageConnectedSocket(socket);
                mServerSocket.close();
                break;
            }
              
        } 
    }
    public void cancle(){
        mServerSocket.close();
    }
    
}
Connection to the client

To develop and maintain the server socket devices to establish a connection, you must first obtain BluetoothDevice the object of the device. Then use this object to get BluetoothSocket and initiate a connection.

The basic process of client connections

  • BluetoothDevice get BluetoothSocket objects through the createRfcommSocketToServiceRecord (UUID)

    Here's UUID to be consistent and server-side

  • Initiate a connection via connect ()

    After performing this method, the system will perform SDP lookup on the remote device, to match the UUID. If the search is successful and the remote device accepts the connection, it shares RFCOMM channel to use during the connection. This time connect () will return. This method is also blocked, if it fails or times out (after 12 seconds), an exception is thrown.

    Call connect () when you want to make sure that the client does not perform discovery operations. If you perform the likelihood of a significant reduction in the speed of the connection, increasing failure

example

private class ConnectThread extend Thread{
    private BluetoothDevice mDevice;
    private BluetoothSocket mSocket;
    public ConnectThread(BluetoothSocket device){
        mDevice = device;
        // 这里的 UUID 需要和服务器的一致
        mSocket = device.createRfcommSocketToServiceRecord(My_UUID);
    }
    
    public void run(){
        // 关闭发现设备
        mBluetoothAdapter.cancelDiscovery();
        try{
             mSocket.connect();
        }catch(IOException connectException){
            try{
                mSocket.close();
            }catch(IOException closeException){
                return;
            }
        }
        // 自定义方法
        manageConnectedSocket(mmSocket);
       
    }
    
    public void cancle(){
        try{
            mSocket.close();
        }cathc(IOException closeException){
            
        }
    }
    
}

Before connecting the call cancleDiscovery()should always call this method before making the connection, and when the call is not necessary to detect whether the scan.

Manage Connections

The two devices establish a connection has BluetoothSocketthrough the Socket can transfer the data between the two devices.

process:

  • Get InputStream and OutputStream
  • Use read (byte []) and write (byte []) read or write stream

Using a configuration file

From Android 3.0, Bluetooth API will support the use of Bluetooth profiles. Bluetooth profiles are applicable to the communication between devices Bluetooth wireless interface specification.

Bluetooth profile is to communicate between devices (Bluetooth device) is a specification

Hands-free profile is an example, for connection to a wireless headset phone, the two devices must support the Handsfree profile. We can also implement interfaces BluetoothProfileto write your own classes to support certain Bluetooth profiles. Android API provides an implementation of several of the following Bluetooth profiles:

  • Headset : Headset Profile provides support for Bluetooth headsets. This configuration file is also provided a mobile phone and a Bluetooth headset to communicate a norm. Use BluetoothHeadset class for interprocess communication to control the Bluetooth headset agency services. This class includes AT command support.
  • A2DP: Advanced Audio Distribution Profile (A2DP). Defines how high quality audio streaming and Bluetooth connection, from one device to another device. BluetoothAdp class, is used to control the Bluetooth A2DP services through inter-process communication (IPC) agent.
  • Health equipment: Android 4.0 (API 14) introduces support for the Bluetooth Health Device Profile (HDP) is. This allows us to create applications that can be used with Bluetooth-enabled Bluetooth devices to communicate health. (Heart rate detector, the blood glucose meter, thermometer, etc.). Detailed configuration To view the health device profile.

The basic steps for configuration files

  • Get the default adapter BluetoothAdapter
  • Use getProfileProxy(), establish a connection to the configuration file proxy object configuration files are associated.
  • Set up listeners BluetoothProfile.ServiceListener. This monitoring will be at the client connects to the service or disconnect service connection when sending notifications.
  • In onServiceConnected()obtaining the configuration file proxy object handler.
  • After obtaining the profile proxy object, loin can be used to monitor a connection state and perform other operations with the configuration file.

Examples: How to connect to the proxy object BluetoothHeadset, to be able to control the Headset Profile:

BluetoothHeadset mBluetoothHeadset;
// 获取默认蓝牙适配器
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// 设置监听(监听连接状态)
private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener(){
    public void onServiceConnected(int profile,BluetoothProfile proxy){
        if(profile == BluetoothProfile.HEADSET){
            mBluetoothHeadset = (BluetoothHeadset)
        }
    }
    public void onServiceDisconnected(int profile){
        if(profile == BluetoothProfile.HEADSET){
            mBluetoothHeadset = null;
        }
    }
}

// 建立与配置文件代理的连接
mBluetoothAdapter.getProfileProxy(contenxt,mProfileListener,BluetoothProfile.HEADSET);
// 使用 mBluetoothHeadset 代理内部的方法

// 使用完毕后关闭
mBluetoothAdapter.closeProfileProxy(mBluetoothHeadset);
Vendor-specific AT commands

Starting Android 3.0. Applications can register to accept the system broadcast (such as Plantronics + XEVENT command) (that is to say our application can accept a Bluetooth headset provider predefined commands) predefined headphone sent vendor-specific AT commands. Such as: the application can accept the broadcast device indicates battery connected, and notifies the user or take other action as required. Use ACTION_VENDOR_SPECIFIC_HEADSET_EVENT create broadcast receivers intent, Handle headset vendor-specific AT commands.

Health Device Profile

Android 4.0 introduces support for the Bluetooth Health Device Profile (HDP) is. You can use our application using Bluetooth health device with Bluetooth-enabled communication (heart rate detector, glucose meters, thermometers, scales)

Application created HDP:

  • Gets BluetoothHealth proxy object

    Similar to the conventional headset and A2DP. HEALTH ServiceListener use and profile type parameter to call getProfileProxy (), to establish a connection and configuration file proxy object.

  • BluetoothHealthCallback create and register acts as a healthy application configuration (BluetoothHealthAPPConfiguration) collection equipment

  • Establish a connection to health equipment

  • After successfully connecting to the healthcare device, read and write file descriptors to use equipment operating health

  • When finished, close the health channel and cancel the registration of the application, the channel will be closed for an extended period.

to sum up:

About the general connection communication between Bluetooth devices and Bluetooth devices Normal

  • Acquisition system unique Bluetooth adapter BluetoothAdapter by getDefaultAdapter method of (if the return is null then the device does not support Bluetooth)
  • Whether by isEnable method BluetoothAdapter judgment has been opened Bluetooth
  • You can turn on Bluetooth by BluetoothAdapter.ACTION_REQUEST_ENABLE intent, it can also be directly .enable turn on Bluetooth
  • StartDiscovery found by calling the open peripheral devices (for 12 seconds), the time required to register a broadcast receiver to accept a Bluetooth device discovery (not close this operation)
  • You can establish a connection via BluetoothDevice, (divided into client and server similar to Socket connection)
  • Then after establishing the connection may be obtained by the flow inside the reader to communicate BluetoothSocket

(Similar products Bluetooth headset, electronic scales, etc.) on Bluetooth devices and Bluetooth equipment

This is achieved by the communication between the proxy configuration file to achieve.

It has a corresponding profile proxy class. Specific operations are done by this object.

Character good.jpg

Guess you like

Origin www.cnblogs.com/sydmobile/p/11129430.html
Recommended