android 官方文档 个人翻译 Bluetooth 蓝牙

背景:由于在不断扩张android应用的功能 同时也是扩充自己能力   自己花了几个小时将 android官方文档中的 Bluetooth 一节进行了翻译  (由于计算机方面知识积累不够

  所以有些地方是自己按照字面翻译的   请多多包涵)


全文全都是自己手动翻译    如果喜欢或者转载 请注明出处  http://blog.csdn.net/callmejason/article/details/44567973  


The Android platform includes support for the Bluetooth network stack, which allows a device to wirelessly exchange data with other Bluetooth devices. The application framework provides access to the Bluetooth functionality through the Android Bluetooth APIs. These APIs let applications wirelessly connect to other Bluetooth devices, enabling point-to-point and multipoint wireless features.

Android平台包括对蓝牙通讯站的支持,这个允许设备通过无线方式与其他蓝牙设备交换数据。应用框架提供通过android蓝牙API对蓝牙功能的访问。这些API让应用能无线地连接其他蓝牙设备,使得点对点,点对多点的功能成为可能。

Using the Bluetooth APIs, an Android application can perform the following:

通过使用蓝牙的API,一个android应用能够获取一下功能

· Scan for other Bluetooth devices

· 扫描其他蓝牙设备

· Query the local Bluetooth adapter for paired Bluetooth devices

· 为本地的蓝牙设备适配器查询适配的蓝牙设备

· Establish RFCOMM channels

· 建立RFCOMM 通道

· Connect to other devices through service discovery

· 通过服务发现功能来与其他设备进行连接

· Transfer data to and from other devices

· 传输来自或者传输给其他设备

· Manage multiple connections

· 管理多个连接

This document describes how to use Classic Bluetooth. Classic Bluetooth is the right choice for more battery-intensive operations such as streaming and communicating between Android devices. For Bluetooth devices with low power requirements, Android 4.3 (API Level 18) introduces API support for Bluetooth Low Energy. To learn more, seeBluetooth Low Energy.

这个文档描述了怎么样使用 “典型的蓝牙”,“典型的蓝牙”对于一些耗电的操作是很正确的选择,例如流操作还有android设备间的通讯。对于一些不耗电的蓝牙设备来讲,Android 4.3 (API Level 18)引进了一些对低电量的蓝牙设备的支持,更多请看http://wear.techbrood.com/guide/topics/connectivity/bluetooth-le.html

The Basics

基础

 

This document describes how to use the Android Bluetooth APIs to accomplish the four major tasks necessary to communicate using Bluetooth: setting up Bluetooth, finding devices that are either paired or available in the local area, connecting devices, and transferring data between devices.

这篇文档描述了怎么样去使用android的蓝牙API来完成使用蓝牙的四大主要通讯任务:

设置蓝牙,查找本地范围内能查找到的的或者可适配的蓝牙设备,连接设备, 在设备间传输数据

All of the Bluetooth APIs are available in the android.bluetooth package. Here's a summary of the classes and interfaces you will need to create Bluetooth connections:

所有的蓝牙API都在android.bluetooth包中,这里是对你创建蓝牙连接所需要的类和接口的总结

BluetoothAdapter

Represents the local Bluetooth adapter (Bluetooth radio). The BluetoothAdapter is the entry-point for all Bluetooth interaction. Using this, you can discover other Bluetooth devices, query a list of bonded (paired) devices, instantiate a BluetoothDevice using a known MAC address, and create a BluetoothServerSocket to listen for communications from other devices.

蓝牙适配器

  展现本地蓝牙适配器(蓝牙无线电)

  蓝牙适配器是所有的蓝牙相互工作的入口,使用蓝牙适配器,你可以发现其他的蓝牙设备,查询出一列可配对的设备,实例化一个蓝牙设备需要用已知的MAC地址,并且创建一个“蓝牙服务器套接字(BluetoothServerSocket)”来对来自其他设备的通讯进行监听

BluetoothDevice

Represents a remote Bluetooth device. Use this to request a connection with a remote device through a BluetoothSocket or query information about the device such as its name, address, class, and bonding state.

蓝牙设备

   展现远程的蓝牙设备。使用这个是为了通过“蓝牙套接字”或者查询设备的信息如名字,类还有绑定状态 方式 来请求对远程设备进行通讯

BluetoothSocket

Represents the interface for a Bluetooth socket (similar to a TCP Socket). This is the connection point that allows an application to exchange data with another Bluetooth device via InputStream and OutputStream.

蓝牙套接字

   展现蓝牙套接字的接口(和TCP套接字相似)。这个是允许应用通过输入输出流来与其他蓝牙设备进行数据交换的连接点

BluetoothServerSocket

Represents an open server socket that listens for incoming requests (similar to a TCPServerSocket). In order to connect two Android devices, one device must open a server socket with this class. When a remote Bluetooth device makes a connection request to the this device, the BluetoothServerSocket will return a connected BluetoothSocket when the connection is accepted.

蓝牙服务器套接字

  展现一个开放的服务器套接字 能对即将来临的请求进行监听(和TCP服务器套接字相似)。为了连接两个android设备,其中一个设备必须开放这个类的服务器套接字。当一个远程的蓝牙设备对当前设备提出连接请求时,连接请求接受时,蓝牙服务器套接字会返回一个已连接的蓝牙套接字

BluetoothClass

Describes the general characteristics and capabilities of a Bluetooth device. This is a read-only set of properties that define the device's major and minor device classes and its services. However, this does not reliably describe all Bluetooth profiles and services supported by the device, but is useful as a hint to the device type.

蓝牙类

   描述蓝牙设备整体的特征。这个是只可读的属性集定义了设备主要的和次要的设备类以及其服务。然而,这个不能很可靠地描述所有的蓝牙简介和设备支持的服务,这个只能作为对设备类型的一个提示

BluetoothProfile

An interface that represents a Bluetooth profile. A Bluetooth profile is a wireless interface specification for Bluetooth-based communication between devices. An example is the Hands-Free profile. For more discussion of profiles, see Working with Profiles

蓝牙简介(配置文件?)

   一个展现蓝牙简介的接口。一个蓝牙简介是一个规范两个设备通讯的无线接口。一个例子就是免提简介 。更多请看http://wear.techbrood.com/guide/topics/connectivity/bluetooth.html#Profiles

 

BluetoothHeadset

Provides support for Bluetooth headsets to be used with mobile phones. This includes both Bluetooth Headset and Hands-Free (v1.5) profiles.

蓝牙耳机

提供对可用于手机的蓝牙耳机提供支持。这个包括蓝牙耳机和免提简介

BluetoothA2dp

Defines how high quality audio can be streamed from one device to another over a Bluetooth connection. "A2DP" stands for Advanced Audio Distribution Profile.

蓝牙Ad2p

  定义能够通过蓝牙流传输音频的质量。"A2DP"代表着高级音频分配模式

BluetoothHealth

Represents a Health Device Profile proxy that controls the Bluetooth service.

蓝牙健康

  展现一种健康的控制蓝牙服务的设备配置文件代理

BluetoothHealthCallback

An abstract class that you use to implement BluetoothHealth callbacks. You must extend this class and implement the callback methods to receive updates about changes in the application’s registration state and Bluetooth channel state.

蓝牙健康回调

   一个你可以继承蓝牙健康回调的抽象类。你必须扩展这个类实现回调方法接收关于在应用程序的注册状态和蓝牙信道状态变化的更新。

BluetoothHealthAppConfiguration

Represents an application configuration that the Bluetooth Health third-party application registers to communicate with a remote Bluetooth health device.

蓝牙健康APP配置

表示应用程序的配置,蓝牙健康的第三方应用寄存器与远程蓝牙健康设备通信。BluetoothProfile.ServiceListener

An interface that notifies BluetoothProfile IPC clients when they have been connected to or disconnected from the service (that is, the internal service that runs a particular profile).

蓝牙简介.服务监听器

  一个接口通知 蓝牙简介IPC客户端当他们被连接或断开了与服务(即,内部服务运行一个特定的简介)。

Bluetooth Permissions

蓝牙许可

 

In order to use Bluetooth features in your application, you must declare the Bluetooth permissionBLUETOOTH. You need this permission to perform any Bluetooth communication, such as requesting a connection, accepting a connection, and transferring data.

为了在你的应用中使用蓝牙的特点,你必须声明蓝牙许可,你需要这个许可才能来实施任何的蓝牙通讯,比如请求连接,接受连接,并且传输数据

If you want your app to initiate device discovery or manipulate Bluetooth settings, you must also declare the BLUETOOTH_ADMIN permission. Most applications need this permission solely for the ability to discover local Bluetooth devices. The other abilities granted by this permission should not be used, unless the application is a "power manager" that will modify Bluetooth settings upon user request. Note: If you use BLUETOOTH_ADMIN permission, then you must also have the BLUETOOTHpermission.

Declare the Bluetooth permission(s) in your application manifest file. For example:

如果你想让你的应用程序启动设备发现或操纵蓝牙设置,你还必须声明 bluetooth_admin 许可。大多数应用程序需要此权限仅用于发现本地蓝牙设备的能力。不能使用其他能力的声明,除非该应用程序是一个“电源管理”,在用户要求下将修改蓝牙设置。注意:如果你使用   bluetooth_admin 权限,那么你也一定有 bluetooth权限。

在你的应用程序清单文件在用户要求。例如:

 
<manifest ... >
  <uses-permission android:name="android.permission.BLUETOOTH" />
  ...
</manifest>

See the <uses-permission> reference for more information about declaring application permissions.

Setting Up Bluetooth

设置蓝牙

 

Figure 1: The enabling Bluetooth dialog.

Before your application can communicate over Bluetooth, you need to verify that Bluetooth is supported on the device, and if so, ensure that it is enabled.

If Bluetooth is not supported, then you should gracefully disable any Bluetooth features. If Bluetooth is supported, but disabled, then you can request that the user enable Bluetooth without leaving your application. This setup is accomplished in two steps, using theBluetoothAdapter.

图像一:启用蓝牙对话框

在你的应用能够和其他蓝牙设备通讯前,你需要验证这个设备是支持蓝牙的,如果是这样,确保蓝牙已经启用。如果蓝牙是支持的,但是没有启用,你可以请求用户启用蓝牙而不用离开你的应用,这个设置只需两步,使用蓝牙适配器

1. Get the BluetoothAdapter

The BluetoothAdapter is required for any and all Bluetooth activity. To get the BluetoothAdapter, call the static getDefaultAdapter() method. This returns aBluetoothAdapter that represents the device's own Bluetooth adapter (the Bluetooth radio). There's one Bluetooth adapter for the entire system, and your application can interact with it using this object. If getDefaultAdapter() returns null, then the device does not support Bluetooth and your story ends here. For example:

1.获得蓝牙适配器

   对于任何的蓝牙操作来讲,蓝牙适配器都是必须的。为了获取蓝牙适配器,使用静态方法getDefaultAdapter()。这个会返回一个能展现设备所有的蓝牙适配器(蓝牙无线电)的蓝牙适配器。对于整个系统来讲,只需要一个蓝牙适配器,你的应用可以通过使用这个对象来和它进行工作

  如果对象返回为空,这个说明设备不支持蓝牙

2. 

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

3. 

4. Enable Bluetooth

Next, you need to ensure that Bluetooth is enabled. Call isEnabled() to check whether Bluetooth is currently enable. If this method returns false, then Bluetooth is disabled. To request that Bluetooth be enabled, call startActivityForResult() with the ACTION_REQUEST_ENABLE action Intent. This will issue a request to enable Bluetooth through the system settings (without stopping your application). For example:

  启用蓝牙

下一步,你需要确认蓝牙是否已经开启,使用isEnabled()方法来检查蓝牙目前是否开启

如果这个方法返回false,说明蓝牙没有开启,为了对没有开启的蓝牙进行请求,你需要使用action ACTION_REQUEST_ENABLE intent 和 startActivityForResult()方法

5. 

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

6. 

A dialog will appear requesting user permission to enable Bluetooth, as shown in Figure 1. If the user responds "Yes," the system will begin to enable Bluetooth and focus will return to your application once the process completes (or fails).

当请求开启蓝牙时一个对话框会出现在用户面前,就像图一里显示的一样。如果用户响应的是yes,系统就会开始开启蓝牙并且只要操作成功(失败)焦点就会回到你的应用

7. 

The REQUEST_ENABLE_BT constant passed to startActivityForResult() is a locally defined integer (which must be greater than 0), that the system passes back to you in your onActivityResult()implementation as the requestCode parameter.

 request_enable_bt 变量传递给 startactivityforresult() 是局部定义的整数(必须大于0),系统传递给你的是你 onactivityresult()中的 requestCode 参数。

If enabling Bluetooth succeeds, your activity receives the RESULT_OK result code in theonActivityResult() callback. If Bluetooth was not enabled due to an error (or the user responded "No") then the result code is RESULT_CANCELED.

如果开启蓝牙成功,你的activityonActivityResult()中会收到RESULT_OK。如果蓝牙由于错误没有开启(或者由于用户响应为NO),结果返回的就是RESULT_CANCELED

8. 

Optionally, your application can also listen for the ACTION_STATE_CHANGED broadcast Intent, which the system will broadcast whenever the Bluetooth state has changed. This broadcast contains the extra fields EXTRA_STATE and  EXTRA_PREVIOUS_STATE, containing the new and old Bluetooth states, respectively. Possible values for these extra fields are STATE_TURNING_ONSTATE_ON,STATE_TURNING_OFF, and STATE_OFF. Listening for this broadcast can be useful to detect changes made to the Bluetooth state while your app is running.

可选的,如果你的应用可以监听ACTION_STATE_CHANGED 广播意图,不管蓝牙状态有没有变系统都会广播。广播包括额外的领域 EXTRA_STATE  EXTRA_PREVIOUS_STATE,分别包括新的和旧的蓝牙状态,对于这些领域的可能的值是STATE_TURNING_ONSTATE_ON,STATE_TURNING_OFF, and STATE_OFF对这些广播的监听能在你应用运行时探测蓝牙状态变化

Tip: Enabling discoverability will automatically enable Bluetooth. If you plan to consistently enable device discoverability before performing Bluetooth activity, you can skip step 2 above. Read about enabling discoverability, below.

提示:开启可发现性会导致蓝牙自动开启。如果你打算开启设备的可见性,你可以跳过以上2步。阅读关于 开启可发现性,下面。

Finding Devices

 

Using the BluetoothAdapter, you can find remote Bluetooth devices either through device discovery or by querying the list of paired (bonded) devices.

Device discovery is a scanning procedure that searches the local area for Bluetooth enabled devices and then requesting some information about each one (this is sometimes referred to as "discovering," "inquiring" or "scanning"). However, a Bluetooth device within the local area will respond to a discovery request only if it is currently enabled to be discoverable. If a device is discoverable, it will respond to the discovery request by sharing some information, such as the device name, class, and its unique MAC address. Using this information, the device performing discovery can then choose to initiate a connection to the discovered device.

Once a connection is made with a remote device for the first time, a pairing request is automatically presented to the user. When a device is paired, the basic information about that device (such as the device name, class, and MAC address) is saved and can be read using the Bluetooth APIs. Using the known MAC address for a remote device, a connection can be initiated with it at any time without performing discovery (assuming the device is within range).

Remember there is a difference between being paired and being connected. To be paired means that two devices are aware of each other's existence, have a shared link-key that can be used for authentication, and are capable of establishing an encrypted connection with each other. To be connected means that the devices currently share an RFCOMM channel and are able to transmit data with each other. The current Android Bluetooth API's require devices to be paired before an RFCOMM connection can be established. (Pairing is automatically performed when you initiate an encrypted connection with the Bluetooth APIs.)

The following sections describe how to find devices that have been paired, or discover new devices using device discovery.

查找设备

使用蓝牙适配器 ,你可以通过查询表配对找到远程蓝牙设备可以通过设备发现或(配对)设备。

设备发现是一种扫描程序搜索本地蓝牙功能的设备,然后请求每一个设备信息(这是有时被称为“发现”,“查询”或“扫描”)。然而,局域网内的蓝牙设备将响应发现请求仅当它是目前能够发现的。如果一个设备是可发现的,它会响应发现请求并共享一些信息,比如设备名称,类别,并以其独特的MAC地址。使用此信息,执行发现的设备可以选择发起一个连接到被发现的设备。

 

Note: Android-powered devices are not discoverable by default. A user can make the device discoverable for a limited time through the system settings, or an application can request that the user enable discoverability without leaving the application. How to enable discoverability is discussed below.

注:Android设备默认是无法发现的。用户可以使设备可在有限的时间内通过系统设置,或者应用程序可以要求用户开启可发现性而无需离开应用程序。如何开启可发现性看下文。

Querying paired devices

Before performing device discovery, its worth querying the set of paired devices to see if the desired device is already known. To do so, call getBondedDevices(). This will return a Set ofBluetoothDevices representing paired devices. For example, you can query all paired devices and then show the name of each device to the user, using an ArrayAdapter:

查询配对设备

执行设备发现之前,查询那些配对过的设备是否在是很值得的。为此,使用 getbondeddevices()方法。这将返回一系列bluetoothdevices配对设备。例如,你可以查询所有配对设备然后显示每个设备的名称的用户,使用一个ArrayAdapter:

 

 
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());
    }
}

All that's needed from the BluetoothDevice object in order to initiate a connection is the MAC address. In this example, it's saved as a part of an ArrayAdapter that's shown to the user. The MAC address can later be extracted in order to initiate the connection. You can learn more about creating a connection in the section about Connecting Devices.

MAC地址是来自BluetoothDevice 对象为了启动连接所需要的东西。在本例中,将它保存为一个ArrayAdapter的一部分显示给用户。为了启动连接MAC地址在之后可以提取出来。你可以了解更多关于创造的部分中的一个连接 连接设备。

 

Discovering devices

To start discovering devices, simply call startDiscovery(). The process is asynchronous and the method will immediately return with a boolean indicating whether discovery has successfully started. The discovery process usually involves an inquiry scan of about 12 seconds, followed by a page scan of each found device to retrieve its Bluetooth name.

Your application must register a BroadcastReceiver for the ACTION_FOUND Intent in order to receive information about each device discovered. For each device, the system will broadcast theACTION_FOUND Intent. This Intent carries the extra fields EXTRA_DEVICE and EXTRA_CLASS, containing aBluetoothDevice and a BluetoothClass, respectively. For example, here's how you can register to handle the broadcast when devices are discovered:

发现设备

开始发现设备,只需调用 startdiscovery()。这个过程是异步方法将立即返回一个布尔值,指示是否发现已成功启动。发现过程通常需要约12秒的查询扫描,其次是页面扫描每个发现的设备来检索蓝牙名称。

为了获得有关每个装置中发现的信息 你的应用程序必须注册为 action_found 。对于每一个设备,系统将广播theaction_found 意图。这种意图带着额外的域 extra_device  extra_class,分别含有abluetoothdevice 和 bluetoothclass。例如,这里是当设备被发现时你可以怎么样注册处理广播:

 
// 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

All that's needed from the BluetoothDevice object in order to initiate a connection is the MAC address. In this example, it's saved as a part of an ArrayAdapter that's shown to the user. The MAC address can later be extracted in order to initiate the connection. You can learn more about creating a connection in the section about Connecting Devices.

MAC地址所有来自蓝牙设备 对象中用来启动连接所需要的。在本例中,将它保存为一个ArrayAdapter的显示给用户的一部分。为了启动连接之后MAC地址可以提取出来。你可以了解更多关于创造的部分中的一个连接 连接设备。

Caution: Performing device discovery is a heavy procedure for the Bluetooth adapter and will consume a lot of its resources. Once you have found a device to connect, be certain that you always stop discovery with cancelDiscovery() before attempting a connection. Also, if you already hold a connection with a device, then performing discovery can significantly reduce the bandwidth available for the connection, so you should not perform discovery while connected.

注意: 执行发现设备对于蓝牙适配器来讲是重过程,会消耗大量的资源。一旦你找到了一个设备连接,你必须确定总是在试图连接之前用 canceldiscovery() 停下设备发现。另外,如果你已经拥有一个设备的连接,然后执行发现可以显着减少可用的连接带宽,所以你不应该在连接执行发现。

Enabling discoverability

If you would like to make the local device discoverable to other devices, callstartActivityForResult(Intent, int) with the ACTION_REQUEST_DISCOVERABLE action Intent. This will issue a request to enable discoverable mode through the system settings (without stopping your application). By default, the device will become discoverable for 120 seconds. You can define a different duration by adding the EXTRA_DISCOVERABLE_DURATION Intent extra. The maximum duration an app can set is 3600 seconds, and a value of 0 means the device is always discoverable. Any value below 0 or above 3600 is automatically set to 120 secs). For example, this snippet sets the duration to 300:

开启可发现

如果你想使本地设备可以被其他设备发现使用startactivityforresult(Intent,int)  action 为 action_request_discoverable 的意图。这将发出一个请求,通过系统设置使发现模式(不停止应用程序)。默认情况下,该设备将成为明显的120秒。你可以通过添加 extra_discoverable_duration 意图额外定义不同的时间。一个应用程序可以设置最大持续时间为3600秒,0的值表示设备总是发现。任何值低于0或高于3600是自动设定为120秒)。例如,这段代码设置时间300:

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

Figure 2: The enabling discoverability dialog.

A dialog will be displayed, requesting user permission to make the device discoverable, as shown in Figure 2. If the user responds "Yes," then the device will become discoverable for the specified amount of time. Your activity will then receive a call to theonActivityResult()) callback, with the result code equal to the duration that the device is discoverable. If the user responded "No" or if an error occurred, the result code will be RESULT_CANCELED.

Note: If Bluetooth has not been enabled on the device, then enabling device discoverability will automatically enable Bluetooth.

The device will silently remain in discoverable mode for the allotted time. If you would like to be notified when the discoverable mode has changed, you can register a BroadcastReceiver for the ACTION_SCAN_MODE_CHANGEDIntent. This will contain the extra fields EXTRA_SCAN_MODE and EXTRA_PREVIOUS_SCAN_MODE, which tell you the new and old scan mode, respectively. Possible values for each areSCAN_MODE_CONNECTABLE_DISCOVERABLESCAN_MODE_CONNECTABLE, or SCAN_MODE_NONE, which indicate that the device is either in discoverable mode, not in discoverable mode but still able to receive connections, or not in discoverable mode and unable to receive connections, respectively.

You do not need to enable device discoverability if you will be initiating the connection to a remote device. Enabling discoverability is only necessary when you want your application to host a server socket that will accept incoming connections, because the remote devices must be able to discover the device before it can initiate the connection.

图2:启用发现对话框 。

会显示一个对话框,请求用户权限使装置可发现,如图2所示。如果用户回答“yes”然后设备将成为明显的在指定的时间量。你的活动将接收到使用 theonactivityresult())回调,结果码等于设备可被发现的时间。如果用户回答“no”,或者如果发生错误,结果代码将 result_canceled。

注意:如果蓝牙 尚未启用,开启设备可发现将自动启用蓝牙。

设备将在分配的时间内静静地停留在发现模式。如果你想模式变了的时候得到通知,你可以 action_scan_mode_changed意图注册一个BroadcastReceiver。这将包含额外的域 extra_scan_mode 或者 extra_previous_scan_mode,这两个将分别告诉你新的和旧的扫描方式。可能的值为每个arescan_mode_connectable_discoverable, scan_mode_connectable 或者scan_mode_none,这个将分别显示装置是在不可发现模式发现模式,但仍能接收连接或者是不可发现模式,无法接收连接。

如果你将发起连接到远程设备你不需要使设备可发现。其中可发现是只需要在你希望你的应用程序的主机服务器套接字将接受传入的连接,因为远程设备必须能够发现装置才可以启动连接。

Connecting Devices

 

In order to create a connection between your application on two devices, you must implement both the server-side and client-side mechanisms, because one device must open a server socket and the other one must initiate the connection (using the server device's MAC address to initiate a connection). The server and c lient are considered connected to each other when they each have a connectedBluetoothSocket on the same RFCOMM channel. At this point, each device can obtain input and output streams and data transfer can begin, which is discussed in the section about Managing a Connection. This section describes how to initiate the connection between two devices.

The server device and the client device each obtain the required BluetoothSocket in different ways. The server will receive it when an incoming connection is accepted. The client will receive it when it opens an RFCOMM channel to the server.

Figure 3: The Bluetooth pairing dialog.

One implementation technique is to automatically prepare each device as a server, so that each one has a server socket open and listening for connections. Then either device can initiate a connection with the other and become the client. Alternatively, one device can explicitly "host" the connection and open a server socket on demand and the other device can simply initiate the connection.

连接设备

为了在两个设备中的应用程序之间建立一个连接,你必须实现服务器端和客户端的机制,因为一个设备必须打开服务器套接字,另一个必须启动连接(使用服务器设备的MAC地址发起连接)。他们每一个在同一个RFCOMM通道都有一个已连接的蓝牙套接字时,服务器和客户端是彼此连接时 。在这一点上,每个装置可获得的输入和输出流并且数据传输可以开始,这是一节中所讨论的关于 管理连接。本节介绍了如何两个设备之间启动连接。

服务器装置和客户端装置的每个获得所需的 bluetoothsocket 方式不同。当到来的连接被接受服务器将收到bluetoothsocket 。客户将收到它时,它打开一个RFCOMM通道到服务器。

图3:蓝牙 配对对话框。

一种实现技术是自动准备每个设备作为服务器,使每一个服务器套接字打开并监听连接。然后可以开始和其他连接成为客户。另外,一个设备可以根据需要明确“主机”的连接和开放服务器套接字这样其他设备可以启动连接。

Note: If the two devices have not been previously paired, then the Android framework will automatically show a pairing request notification or dialog to the user during the connection procedure, as shown in Figure 3. So when attempting to connect devices, your application does not need to be concerned about whether or not the devices are paired. Your RFCOMM connection attempt will block until the user has successfully paired, or will fail if the user rejects pairing, or if pairing fails or times out.

注:如果两 设备之前没有配对,那么Android框架会自动连接过程中显示一个配对请求通知或对话框给用户,如图3所示。所以尝试连接设备时,应用程序不需要关心是否设备的配对。你的RFCOMM连接尝试将阻塞直到用户成功配对,或者如果该用户拒绝配对失败,或者如果配对失败或超时。

Connecting as a server

When you want to connect two devices, one must act as a server by holding an openBluetoothServerSocket. The purpose of the server socket is to listen for incoming connection requests and when one is accepted, provide a connected BluetoothSocket. When the BluetoothSocket is acquired from the BluetoothServerSocket, the BluetoothServerSocket can (and should) be discarded, unless you want to accept more connections.

作为一个服务器连接

当你想要连接两个设备,一个作为持开放的bluetoothserversocket服务器。服务器套接字的目的是监听传入的连接请求,当一个接受,提供一个连接 bluetoothsocket。当 bluetoothsocket 从 获得来自bluetoothserversocket bluetoothserversocket ,bluetoothserversocket 可以(也应该)被丢弃,除非你想接受更多的连接。

About UUID

A Universally Unique Identifier (UUID) is a standardized 128-bit format for a string ID used to uniquely identify information. The point of a UUID is that it's big enough that you can select any random and it won't clash. In this case, it's used to uniquely identify your application's Bluetooth service. To get a UUID to use with your application, you can use one of the many random UUID generators on the web, then initialize aUUID with fromString(String).

Here's the basic procedure to set up a server socket and accept a connection:

1. Get a BluetoothServerSocket by calling thelistenUsingRfcommWithServiceRecord(String, UUID).

The string is an identifiable name of your service, which the system will automatically write to a new Service Discovery Protocol (SDP) database entry on the device (the name is arbitrary and can simply be your application name). The UUID is also included in the SDP entry and will be the basis for the connection agreement with the client device. That is, when the client attempts to connect with this device, it will carry a UUID that uniquely identifies the service with which it wants to connect. These UUIDs must match in order for the connection to be accepted (in the next step).

2. 

3. Start listening for connection requests by callingaccept().

This is a blocking call. It will return when either a connection has been accepted or an exception has occurred. A connection is accepted only when a remote device has sent a connection request with a UUID matching the one registered with this listening server socket. When successful, accept() will return a connected BluetoothSocket.

4. 

5. Unless you want to accept additional connections, call close().

This releases the server socket and all its resources, but does not close the connectedBluetoothSocket that's been returned by accept(). Unlike TCP/IP, RFCOMM only allows one connected client per channel at a time, so in most cases it makes sense to call close() on theBluetoothServerSocket immediately after accepting a connected socket.

6. 

The accept() call should not be executed in the main activity UI thread because it is a blocking call and will prevent any other interaction with the application. It usually makes sense to do all work with a BluetoothServerSocket or BluetoothSocket in a new thread managed by your application. To abort a blocked call such as accept(), call close() on the BluetoothServerSocket (or BluetoothSocket) from another thread and the blocked call will immediately return. Note that all methods on aBluetoothServerSocket or BluetoothSocket are thread-safe.

关于UUID

一个通用唯一标识符(UUID)是一个字符串ID用于唯一标识信息的一个标准的128位格式。一个UUID关键是足够大,你可以选择任何随机的,它不会有冲突。在这种情况下,它是用来唯一标识您的应用程序的蓝牙服务。为了得到一个UUID使用您的应用程序,您可以在网络上使用一个随机的UUID生成器,然后 fromstring(字符串)初始化auuid。

这是建立服务器套接字并接受连接的基本程序:

1。通过调用thelistenusingrfcommwithservicerecord得到 bluetoothserversocket (字符串,UUID)。

字符串是你的服务可识别的名称,系统会自动写入一个新的服务发现协议(SDP)设备上的数据库入口(名称是任意的,可以简单地将你的应用程序的名称)。UUID也包括在SDP的入口并且是与客户设备连接的连接协议的基础。那就是,当客户端试图与该设备连接,它将携带一个UUID唯一标识与它想要连接的服务。这些UUID为了连接能接受必须匹配(下一步)。

2。

3。通过调用accept()开始侦听连接请求

这是一个阻塞调用。当一个连接已被接受或发生异常时,它将返回值?只有当远程设备发送连接请求一个能够用监听服务器套接字注册的UUID匹配时,连接才会被接受。成功时, accept() 会返回一个已连接的 bluetoothsocket。

5。除非你愿意接受额外的连接,调用 close()。

这个会释放服务器套接字和它的所有资源,但不关闭由 accept()返回的已连接的bluetoothsocket。不同于TCP/IP,RFCOMM只允许同一时刻内每一个通道只有一个连接的客户端,所以在大多数情况下在thebluetoothserversocket 立即接受连接的套接字后BluetoothServerSocket 之上调用close()是有意义的。

6。 accept() 的调用不应该 在主要活动UI线程,因为它是一个阻塞调用,将阻止任何其他交互应用。它通常是在你应用管理的新线程 通过 bluetoothserversocket 或 bluetoothsocket 做所有的工作。中止一个阻塞调用如 accept(),从另一个线程阻塞中在bluetoothserversocket ()上(或 bluetoothsocket)调用close()被阻塞的调用将立即返回。注意:abluetoothserversocket 或 bluetoothsocket 所有的方法都是线程安全的。

Example

Here's a simplified thread for the server component that accepts incoming connections:

这里是接受传入连接的服务器组件的一个简化的线程:

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

In this example, only one incoming connection is desired, so as soon as a connection is accepted and the BluetoothSocket is acquired, the application sends the acquired BluetoothSocket to a separate thread, closes the BluetoothServerSocket and breaks the loop.

Note that when accept() returns the BluetoothSocket, the socket is already connected, so you shouldnot call connect() (as you do from the client-side).

manageConnectedSocket() is a fictional method in the application that will initiate the thread for transferring data, which is discussed in the section about Managing a Connection.

You should usually close your BluetoothServerSocket as soon as you are done listening for incoming connections. In this example, close() is called as soon as the BluetoothSocket is acquired. You may also want to provide a public method in your thread that can close the private BluetoothSocket in the event that you need to stop listening on the server socket.

在这个例子中,只有一个传入的连接是需要的,只要接受连接和 bluetoothsocket 就会获得,应用程序将获得 bluetoothsocket 到一个单独的线程,关闭 bluetoothserversocket 破坏回路

注意当 accept() 返回 bluetoothsocket,套接字已连接,所以你不应该调用 connect() (当你在客户端操作时)。

manageconnectedsocket() 是在应用程序中,为了数据传送启动线程一个虚构的方法,这个是在 管理连接 这一节讨论的

只要你完成侦听传入的连接你应该常闭 bluetoothserversocket 。在这个例子中,  只要 bluetoothsocket 获得 close()就被调用。您可能还需要你的线程中提供公共方法可以关闭的事件中的私有 BluetoothSocket ,为了停止监听服务器套接字私人 bluetoothsocket 。

Connecting as a client

In order to initiate a connection with a remote device (a device holding an open server socket), you must first obtain a BluetoothDevice object that represents the remote device. (Getting aBluetoothDevice is covered in the above section about Finding Devices.) You must then use theBluetoothDevice to acquire a BluetoothSocket and initiate the connection.

Here's the basic procedure:

1. Using the BluetoothDevice, get a BluetoothSocket by calling createRfcommSocketToServiceRecord(UUID).

This initializes a BluetoothSocket that will connect to the BluetoothDevice. The UUID passed here must match the UUID used by the server device when it opened its BluetoothServerSocket (withlistenUsingRfcommWithServiceRecord(String, UUID)). Using the same UUID is simply a matter of hard-coding the UUID string into your application and then referencing it from both the server and client code.

2. 

3. Initiate the connection by calling connect().

Upon this call, the system will perform an SDP lookup on the remote device in order to match the UUID. If the lookup is successful and the remote device accepts the connection, it will share the RFCOMM channel to use during the connection and connect() will return. This method is a blocking call. If, for any reason, the connection fails or the connect() method times out (after about 12 seconds), then it will throw an exception.

4. 

Because connect() is a blocking call, this connection procedure should always be performed in a thread separate from the main activity thread.

5. 

Note: You should always ensure that the device is not performing device discovery when you callconnect(). If discovery is in progress, then the connection attempt will be significantly slowed and is more likely to fail.

 

作为一个客户端连接

为了发起与远程设备的连接(一个装置保持一个开放的服务器套接字),你必须首先获得 展现远程设备的蓝牙设备对象。(如何得到abluetoothdevice 已经在上面的部分关于 发现设备中覆盖。)你必须使用thebluetoothdevice 获得 bluetoothsocket 和启动连接。

这里的基本程序:

1。使用 蓝牙设备,通过调用 createrfcommsockettoservicerecord(UUID)得到 bluetoothsocket 

这个初始化 bluetoothsocket  将连接到蓝牙设备。UUID经过这里必须匹配服务器装置使用的UUID, bluetoothserversocket UUID和listenusingrfcommwithservicerecord(字符串,UUID))。使用相同的UUID是一件简单的事,硬编码到应用程序的UUID字符串然后引用它从服务器和客户端的代码。

3。通过调用 connect()启动连接。

在这个调用,系统将为远程设备相匹配的UUID进行SDP查找。如果查找成功,远程设备接受连接,在连接的过程中它将分享RFCOMM通道来使用和 connect() 将返回。该方法是一个阻塞调用。如果,出于任何原因,连接失败或 connect() 超时(约12秒后),那么它将抛出一个异常。

4

因为 connect() 是阻塞调用,这个连接的过程应该是一个从单独的线程执行线程的主要活动。

5

注意:当你调用callconnect()你应该确保设备不执行设备发现。如果发现正在执行,然后连接尝试将明显放缓,更可能是失败的。

6

Example

Here is a basic example of a thread that initiates a Bluetooth connection:

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

Notice that cancelDiscovery() is called before the connection is made. You should always do this before connecting and it is safe to call without actually checking whether it is running or not (but if you do want to check, call isDiscovering()).

manageConnectedSocket() is a fictional method in the application that will initiate the thread for transferring data, which is discussed in the section about Managing a Conne ction.

注意 canceldiscovery() 是连接之前被调用。你应该总是连接它之前这样做并且调用它是安全的 需要检查不管它是否正在运行(如果你想检查,调用 isdiscovering())。

manageconnectedsocket() 是在应用程序中启动线程进行数据传送的一个虚构的方法,这一节中所讨论的关于 管理连接

When you're done with your BluetoothSocket, always call close() to clean up. Doing so will immediately close the connected socket and clean up all internal resources.

当你完成了蓝牙的一些操作,总是要调用close方法来清理,这样做会立刻关闭已经连接的套接字并且清理所有的内部资源

Managing a Connection

管理一个连接

 

When you have successfully connected two (or more) devices, each one will have a connectedBluetoothSocket. This is where the fun begins because you can share data between devices. Using theBluetoothSocket, the general procedure to transfer arbitrary data is simple:

1. Get the InputStream and OutputStream that handle transmissions through the socket, viagetInputStream() and getOutputStream(), respectively.

2. Read and write data to the streams with read(byte[]) and write(byte[]).

That's it.

There are, of course, implementation details to consider. First and foremost, you should use a dedicated thread for all stream reading and writing. This is important because both read(byte[]) andwrite(byte[]) methods are blocking calls. read(byte[]) will block until there is something to read from the stream. write(byte[]) does not usually block, but can block for flow control if the remote device is not calling read(byte[]) quickly enough and the intermediate buffers are full. So, your main loop in the thread should be dedicated to reading from the InputStream. A separate public method in the thread can be used to initiate writes to the OutputStream.

当你已经成功连接了两个(或者多个)设备的时候,每一个设备都会有一个已连接的蓝牙套接字。这是最好玩的地方,因为你可以在设备之间传输数据,使用蓝牙套接字,传输任何数据都会很简单

1。通过socket获取InputStreamOutputStream 处理传输,分别通过getinputstream() 和 getoutputstream()

2。通过read()和write()方法读和写数据流

当然,实现细节的考虑。首先,你应该使用一个专用线程来进行所有流的阅读和写作。这很重要,因为read()write() 方法都是阻塞调用。 Read() 将阻塞直到流中有东西可读。Write()并不是进程阻塞,但可以为流量控制阻塞如果远程设备没有足够快地调用read()并且中间缓冲区满了。所以,你的线程中的主回路应致力于从 InputStream读取。线程中的一个单独的公共方法可以用来启动写入OutputStream 

Example

Here's an example of how this might look:

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

The constructor acquires the necessary streams and once executed, the thread will wait for data to come through the InputStream. When read(byte[]) returns with bytes from the stream, the data is sent to the main activity using a member Handler from the parent class. Then it goes back and waits for more bytes from the stream.

Sending outgoing data is as simple as calling the thread's write() method from the main activity and passing in the bytes to be sent. This method then simply calls write(byte[]) to send the data to the remote device.

The thread's cancel() method is important so that the connection can be terminated at any time by closing the BluetoothSocket. This should always be called when you're done using the Bluetooth connection.

For a demonstration of using the Bluetooth APIs, see the Bluetooth Chat sample app.

构造函数需要必要的流,一旦执行,线程会等待数据通过InputStream。 read()方法 从流中返回字节数,使用来自父类Handler成员来将数据 传输到主activity。然后回去等待更多的字节流。

输出数据是从主要活动调用线程 write() 方法和传递的字节一样简单。该方法然后调用 write()发送数据到远程装置。

线程 cancel() 方法是非常重要的,通过关闭 bluetoothsocket连接可以在任何时候终止。当你完成蓝牙连接之后这个方法必须得调用

为了演示使用蓝牙API,看到 蓝牙聊天示例应用程序。

Working with Profiles

通过配置文件工作

 

Starting in Android 3.0, the Bluetooth API includes support for working with Bluetooth profiles. ABluetooth profile is a wireless interface specification for Bluetooth-based communication between devices. An example is the Hands-Free profile. For a mobile phone to connect to a wireless headset, both devices must support the Hands-Free profile.

You can implement the interface BluetoothProfile to write your own classes to support a particular Bluetooth profile. The Android Bluetooth API provides implementations for the following Bluetooth profiles:

· Headset. The Headset profile provides support for Bluetooth headsets to be used with mobile phones. Android provides the BluetoothHeadset class, which is a proxy for controlling the Bluetooth Headset Service via interprocess communication (IPC). This includes both Bluetooth Headset and Hands-Free (v1.5) profiles. The BluetoothHeadset class includes support for AT commands. For more discussion of this topic, see Vendor-specific AT commands

· A2DP. The Advanced Audio Distribution Profile (A2DP) profile defines how high quality audio can be streamed from one device to another over a Bluetooth connection. Android provides theBluetoothA2dp class, which is a proxy for controlling the Bluetooth A2DP Service via IPC.

· Health Device. Android 4.0 (API level 14) introduces support for the Bluetooth Health Device Profile (HDP). This lets you create applications that use Bluetooth to communicate with health devices that support Bluetooth, such as heart-rate monitors, blood meters, thermometers, scales, and so on. For a list of supported devices and their corresponding device data specialization codes, refer to Bluetooth Assigned Numbers at www.bluetooth.org. Note that these values are also referenced in the ISO/IEEE 11073-20601 [7] specification as MDC_DEV_SPEC_PROFILE_ * in the Nomenclature Codes Annex. For more discussion of HDP, see Health Device Profile.

Here are the basic steps for working with a profile:

1. Get the default adapter, as described in Setting Up Bluetooth.

2. Use getProfileProxy() to establish a connection to the profile proxy object associated with the profile. In the example below, the profile proxy object is an instance of BluetoothHeadset.

3. Set up a BluetoothProfile.ServiceListener. This listener notifies BluetoothProfile IPC clients when they have been connected to or disconnected from the service.

4. In onServiceConnected(), get a handle to the profile proxy object.

5. Once you have the profile proxy object, you can use it to monitor the state of the connection and perform other operations that are relevant to that profile.

For example, this code snippet shows how to connect to a BluetoothHeadset proxy object so that you can control the Headset profile:

从Android 3开始,蓝牙API包括对和蓝牙配置文件一起工作的支持一个bluetooth配置文件 是无线设备之间通过蓝牙通信接口规范。一个例子是免提配置文件。一个移动电话连接到一个无线耳机,设备必须支持免提配置文件。

你可以实现接口 bluetoothprofile 写你自己的类来支持一个特定的蓝牙。Android蓝牙API提供了以下蓝牙功能的实现:

耳机。耳机配置文件提供的蓝牙耳机支持。Android提供 bluetoothheadset ·类,是一种通过进程间通信控制蓝牙耳机服务代理(IPC)。这包括蓝牙耳机和免提配置文件(V1.5)。这类包括 bluetoothheadset 支持的AT命令。更多的讨论这个话题,看到 供应商特定的AT命令

·A2DP。高级音频分配模式(A2DP)配置文件定义了如何高质量的音频可以通过蓝牙连接传输从一个设备到另一个设备。Android提供thebluetootha2dp 类,是一种通过IPC控制蓝牙A2DP服务代理。

·健康装置。Android 4.0(API级别14)介绍了支持蓝牙医疗设备的配置文件(HDP)。这使您可以创建使用蓝牙与健康设备支持蓝牙通信的应用程序,如心率监视器,血糖,温度计,体重计,等等。为了一系列支持的设备和相应的设备返回的数据化码,参阅 蓝牙编号 在 www.bluetooth.org。注意,这些值也被引用在ISO / IEEE 11073-20601 [ 7 ]规范mdc_dev_spec_profile_ *在命名法规附件。更多讨论见 HDP,健康设备配置文件。

这是档案工作的基本步骤:

1。获得默认的适配器,如 设置蓝牙的描述。

2。使用 getprofileproxy() 建立与配置文件相关联的文件代理对象 的连接。在下面的例子中,代理对象的是 bluetoothheadset实例。

3。建立 bluetoothprofile.servicelistener。这个监听器通知 bluetoothprofile IPC客户当他们被连接或从服务中断开了。

4。在 onserviceconnected(),获取一个配置文件代理对象的handle

5。一旦你有了配置文件的代理对象,你可以用它来监视连接的状态和执行其他和配置文件相关的操作  例如,这个代码显示了如何连接到 bluetoothheadset 代理对象使您可以控制耳机配置文件

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);

Vendor-specific AT commands

Starting in Android 3.0, applications can register to receive system broadcasts of pre-defined vendor-specific AT commands sent by headsets (such as a Plantronics +XEVENT command). For example, an application could receive broadcasts that indicate a connected device's battery level and could notify the user or take other action as needed. Create a broadcast receiver for theACTION_VENDOR_SPECIFIC_HEADSET_EVENT intent to handle vendor-specific AT commands for the headset.

Health Device Profile

Android 4.0 (API level 14) introduces support for the Bluetooth Health Device Profile (HDP). This lets you create applications that use Bluetooth to communicate with health devices that support Bluetooth, such as heart-rate monitors, blood meters, thermometers, and scales. The Bluetooth Health API includes the classes BluetoothHealthBluetoothHealthCallback, and BluetoothHealthAppConfiguration, which are described in The Basics.

In using the Bluetooth Health API, it's helpful to understand these key HDP concepts:

Concept供应商特定的AT命令

从Android 3开始,应用程序可以注册来接收耳机预先定义的特定于供应商的系统广播(如Plantronics + XEvent命令)。例如,一个应用程序能够接收指出一个连接设备的电池水平的广播,能够通知用户,或采取其他必要的行动。这个action_vendor_specific_headset_event 意图用来为了耳机处理特定厂商命令。

健康设备配置

Android 4.0(API级别14)介绍了支持蓝牙医疗设备模式(HDP)。这使您可以创建使用蓝牙与卫生设备支持蓝牙通信的应用程序,如心率监视器,血糖,温度计,和尺寸。蓝牙API包括健康类 bluetoothhealth, bluetoothhealthcallback bluetoothhealthappconfiguration,这是在基本知识中描述的 。

在使用蓝牙健康API,了解这些关键的HDP的概念是很有帮助的:

Description

Source

A role defined in HDP. A source is a health device that transmits medical data (weight scale, glucose meter, thermometer, etc.) to a smart device such as an Android phone or tablet.

定义在HDP中的角色。资源是有健康设备传播医学数据(重量尺度,葡萄糖计、温度计等)到智能设备如Android手机或平板。

Sink

A role defined in HDP. In HDP, a sink is the smart device that receives the medical data. In an Android HDP application, the sink is represented by aBluetoothHealthAppConfiguration object.

定义在HDP的一个角色,HDP中,一个sink是智能设备接受医疗数据。在一个android HDP应用中 sink 由一个BluetoothHealthAppConfiguration对象表示

Registration

Refers to registering a sink for a particular health device.

用于为一个健康设备注册一个sink

Connection

Refers to opening a channel between a health device and a smart device such as an Android phone or tablet.

用来在健康设备和智能设备间例如android手机和平板间开通一个通道

Creating an HDP Application

Here are the basic steps involved in creating an Android HDP application:

1. Get a reference to the BluetoothHealth proxy object.

Similar to regular headset and A2DP profile devices, you must call getProfileProxy() with aBluetoothProfile.ServiceListener and the HEALTH profile type to establish a connection with the profile proxy object.

2. 

3. Create a BluetoothHealthCallback and register an application configuration (BluetoothHealthAppConfiguration) that acts as a health sink.

4. Establish a connection to a health device. Some devices will initiate the connection. It is unnecessary to carry out this step for those devices.

5. When connected successfully to a health device, read/write to the health device using the file descriptor.

The received data needs to be interpreted using a health manager which implements the IEEE 11073-xxxxx specifications.

6. 

7. When done, close the health channel and unregister the application. The channel also closes when there is extended inactivity.

For a complete code sample that illustrates these steps, see Bluetooth HDP (Health Device Profile).

创建一个HDP的应用

这里是参与创建一个Android程序应用程序的基本步骤:

1。可以参照 bluetoothhealth 代理对象。

类似于普通的耳机,A2DP设备,你必须调用 getprofileproxy() 与abluetoothprofile。servicelistener 和 健康配置文件类型建立档案和与代理对象进行连接。

3。创建一个 bluetoothhealthcallback 和注册一个应用程序配置(bluetoothhealthappconfiguration),作为一个健康的沉。

4。建立一个连接到医疗设备。某些设备将启动连接。对于这些设备不需要进行这一步。

5。当连接成功到医疗设备,读/写使用文件描述符的健康装置。

接收到的数据需要用health manager implement IEEE 11073- xxxxx解释。

7。完成后,关闭健康频道和反注册申请。当之后又延迟的没有活动时通道会被关闭时。

一个完整的代码示例,演示了这些步骤,看到 蓝牙HDP(健康设备配置文件)。

 

 


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值