編輯:關於Android編程
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:
...
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
下一步,你需要確保你的藍牙是打開的,調用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 errZ喎?/kf/ware/vc/" target="_blank" class="keylink">vciAob3IgdGhlIHVzZXIgcmVzcG9uZGVkIA=="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。
SetAll 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.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()); } }
所有事情需要一個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
華為榮耀87月19日上午10點08分,榮耀8將在線上線下同步開賣。很多華為手機的粉絲們都在等待,華為榮耀8真的配置是怎麼樣的呢?下文就讓小編給大家介紹華為榮
首先看一下activity返回數據的結構圖以前我們啟動另外一個activity用的是startActivity(Intent intent)方法 而若想打開另外一個act
一.大致效果~別嫌它丑二.關鍵代碼在注釋中講重點吧。(1)Spinner的布局: car_brand_spinner.xml即為彈出來的下拉列表的布局啦,後面的那個布局就
創建AlertDialog的步驟: 1、創建AlertDialog.Builder對象 2、調用Builder對象的setTitle方法設置標題,setI