android Bluetooth(官方翻译)
Bluetooth
Using the Bluetooth APIs, an Android application can perform the following:
使用蓝牙APIs,一个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
管理多个连接
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 Bluetooth APIs去完成四个主要任务去使用Bluetooth交流:安装Bluetooth,查找配对的设备或者在本地可用的设备,连接设备,在设备间交换数据。
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:
所有类都在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.
代表本地蓝牙适配器(蓝牙监听者),BluetoothAdapter是所有使用Bluetooth对话的入口。使用它可以发现其他Bluetooth设备,查找已经配对的设备的列表,初始化一个BluetoothDevice使用一个知道的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.
代表了远程的Bluetooth设备。远程设备使用它来通过BluetoothSocket发起一个连接或者或者查询设备的名字,地址 ,类名和配对状态
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.
用来通过InputStream和OutputStream交换数据
BluetoothServerSocket
Represents an open server socket that listens for incoming requests (similar to a TCP ServerSocket). 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.
用来监听请求,两个设备为了连接,一个设备必须打开一个server socket通过这个类,当远程蓝牙设备发起一个连接来连接这个设备,BluetoothServerSocket会返回一个已经连接的BluetoothSocket当连接接受时
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
BluetoothHeadset
Provides support for Bluetooth headsets to be used with mobile phones. This includes both Bluetooth Headset and Hands-Free (v1.5) profiles.
提供了蓝牙耳机支持
Defines how high quality audio can be streamed from one device to another over a Bluetooth connection. "A2DP" stands for Advanced Audio Distribution Profile.
定义了高质量的音频通过一个设备到另一个设备的流连接
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.
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).
Bluetooth Permissions
In order to use Bluetooth features in your application, you must declare the Bluetooth permission BLUETOOTH. You need this permission to perform any Bluetooth communication, such as requesting a connection, accepting a connection, and transferring data.
所有使用蓝牙的操作都要声明BLUETOOTH权限
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 BLUETOOTH permission.
如果希望你的程序初始化设备发现或者更多的蓝牙设置,你必须声明BLUETOOTH_ADMIN权限,大部分应用需要 这个权限唯独需要发现本地蓝牙设备的能力,授予此权限的其他能力不应该被使用,除非该应用程序是一个“电源管理”,将根据用户请求修改蓝牙设置。
Declare the Bluetooth permission(s) in your application manifest file. For example:
<manifest ... > <uses-permission android:name="android.permission.BLUETOOTH" /> ... </manifest>
Setting Up Bluetooth
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 the BluetoothAdapter.
如果你的蓝牙不支持,你应该优雅地关闭任何蓝牙特定,如果你的蓝牙支持的但是关闭了,你应该你应该发起 请求来打开你的蓝牙而没有离开你的应用,这个安装使用BluetoothAdapter两步来完成
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 a BluetoothAdapter 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:
BluetoothAdapter被要求任何和所有的Bluetooth activity,使用静态的getDefaultAdapter()方法来获取BluetoothAdapter,返回一个代表自己蓝牙适配器的BluetoothAdapter对象,整个系统只有一个蓝牙设备,你的应用能使用这个对象进行对话,返回getDefaultAdapter()返回null,你的设备是不支持蓝牙的:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { // Device does not support Bluetooth }2.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,代表蓝牙是关闭的,为了请求打开蓝牙,调用startActivityForResult()伴随一个ACTION_REQUEST_ENABLE 的action的intent,这将会发起一个打开系统蓝牙设置的请求(而没有停止你的应用)
if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }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).
一个对话框会跳出让用户打开蓝牙的权限,如图一所示,
If enabling Bluetooth succeeds, your activity receives the RESULT_OK result code in the onActivityResult() callback. If Bluetooth was not enabled due to an error (or the user responded "No") then the result code is RESULT_CANCELED.
如果打开蓝牙成功的,你的Activity会收到RESULT_OK结果码在 onActivityResult()回调中,如果用户选择No则结果码是RESULT_CANCELED
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_ON, STATE_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广播intent,当系统蓝牙状态改变将会发起这个广播,这个广播包含了EXTRA_STATE和EXTRA_PREVIOUS_STATE额外的字段,包含了新的和旧的蓝牙状态分别的,可能 有STATE_TURNING_ON,STATE_ON,STATE_TURNING_OFF和STATE_OFF可能的值,监听广播能够 对于检测蓝牙状态改变是有用的。
Finding Devices(发现设备)
Using the BluetoothAdapter, you can find remote Bluetooth devices either through device discovery or by querying the list of paired (bonded) devices.
使用BluetoothAdapter,你能够打开可见性的设备和已经配对的的设备列表。
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.
设备可见性对于一个扫描程序查找本地打开蓝牙的设备然后请求关于任何一方的某些信息,然而,一个蓝牙设备在本地将会响应一个可见请求只有在当前打开了可见性,如果设备打开可见性的,它将响应可见请求通过分享某些信息,比如设备的名字,类,和它的独一无二的MAC地址,使用这个信息,设备能够操作可见性设备来初始化一个连接
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).
一旦远程设备第一次被连接,一个配对的请求代表用户,当一个设备被配对的,关于设备的基本信息被保存然后可以使用BluetoothAPI去读取,使用一个MAC地址对于一个远程设备,一个连接能够被初始化在任何在可见范围内。
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.)
记住配对和连接之间的区别,已经配对的意味着两个设备是互相认识对方的存在,已经有了一个用来认证的共享的key,然后可以被捕捉对于建立一个可信的连接互相。已经连接意味着设备当前分享一个RFCOMM通道and能够交换数据互相的。当前的Android Bluetooth API要求设备被配对的在一个RFCOMM连接被建立之前。
The following sections describe how to find devices that have been paired, or discover new devices using device discovery.
如下部分描述了如何发现已经配对的设备,或者发现使用设备可见性发现一个新设备。
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 of BluetoothDevices 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()来调用。这将会返回一个已经配对的设备的集合,例如:你可以查询所有已经配对的设备然后显示给用户他们的名字使用一个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地址能够后来被提取到来初始化连接,你能够学习更多关于创建连接在Connecting Devices这部分
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.
为了开启发现设备,简单地调用startDiscovery()。这个进程是同步的,这个方法将会直接返回一个boolean表明可见性是否成功被开启的。发现进程通常牵涉一个12秒的查询扫描,紧接着通过一个page对于一个发现的设备的扫描来检索它的Bluetooth名字。
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 the ACTION_FOUND Intent. This Intent carries the extra fields EXTRA_DEVICE and EXTRA_CLASS, containing a BluetoothDevice and a BluetoothClass, respectively. For example, here‘s how you can register to handle the broadcast when devices are discovered:
你的应用必须注册一个BroadcastReceiver对于一个ACTION_FOUND的intent来接受关于每一个已经发现的设备。对于每一个设备,系统将会广播发起
ACTION_FOUND的intent。这个intent携带EXTRA_DEVICE和EXTRA_CLASS的额外数据,包含一个BluetoothDevice和一个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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。