配色: 字号:
安卓蓝牙中文翻译帮助文档
2013-07-15 | 阅:  转:  |  分享 
  
安卓蓝牙开发帮助文档

安卓平台包含了支持蓝牙网络的软件栈,这使得安卓设备可以和其他的蓝牙设备进行无线

数据交换。通过安卓蓝牙的API函数,应用程序框架提供了访问蓝牙的功能。这些API使得

应用程序可以无线连接到其他的蓝牙设备,并且支持点对点和点对多点。

运用蓝牙API,一个安卓应用程序可以做下面的事

1、扫描其他蓝牙设备

2、查询局部(周围)区域的蓝牙适配器来进行蓝牙设备之间的配对

3、建立RFCOMM通信通道

4、通过服务发现连接到其他设备

5、和其他设备之间互传数据

6、管理多个设备的连接

蓝牙权限

为了在你的应用程序里面使用蓝牙,你必须声明至少2条蓝牙权限中的一条。这2条权限分

别是|BLUETOOTH和BLUETOOTHADMIN

为了执行任何的蓝牙通信动作,例如请连接,接连接,传数据,你必须声明

BLUETOOTH这个权限。

为了蓝牙设备发现和管理蓝牙设,你必须声明BLUETOOTHADMIN这个权限。

如是发现局部区域的蓝牙设备,多数应用程序声明这个权限可以了。这个

权限的其他能一是用的,这个应用程序是powermanger管理的,据

用进行蓝牙设。的是,如你使用了BLUETOOTHADMIN这个权限

必须使用BLUETOOTH这个权限

建立蓝牙

在你的应用程序通过蓝牙通信之,你应?¢£你的设备是支持蓝牙的,如是这?

¢¥是可用的。

如你的设备支持蓝牙,?§currency1你能使用任何蓝牙的功能。如你的设备支持蓝牙,''

是可用,这个“?在?开你的应用程序的提下你可以请用使能蓝牙。这个?作通

过BluetoothAdapter2fi。

1、flBluetoothAdapter蓝牙适配器

BluetoothAdaptermBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();

if(mBluetoothAdapter==null){

//DevicedoesnotsupportBluetooth

}

2、使能蓝牙



if(!mBluetoothAdapter.isEnabled()){

IntentenableBtIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);

}

查?设备

通过BluetoothAdapter,使用设备发现能?·查询?配对???”的蓝牙设备,你可

以?到?程的蓝牙设备?周围的蓝牙设备”。

设备发现是一个扫描的过程,包…‰周围区域?使能了蓝牙的设备`请′个设备

的一些信??这个“??做ˉdiscovering”,ˉinqureing”,ˉscanning””

?在这个周围区域的蓝牙设备如是使能了˙发现?可¨”的,??应这个发现

请。通过分?一些信?,例如设备的?ˇ,—别,和一的理。通过这些信?,

动发现过程?扫描设备”的设备`可以连接周围˙发现的设备。

一一和?程设备建立连接,一个配对请??动现在用面。设备配对了的

,设备的一些信??设备的?ˇ,—别,和一的理”˙¥?了并且可

以通过蓝牙APIa来。运用的?程设备的理,可以在任何“?建立连接?无

须执行发现过程?扫描周围设备,设设备在围之?”

??配对和?连接一点?。?配对?o2个设备?道了对的?在,

?分?一个£的?,可以建立一个?连接。?连接?o设备分??一

个RFCOMM通信通道可以互传数据。现在的安卓蓝牙API设备在建立一个

RFCOMM通信通道之?进行配对。?你用蓝牙API一个?连接的“?配对是

动进行的”

下面的部分?了如何通过设备发现能来发现?配对了设备和??发现的设备。

查询配对设备

在执行设备发现之,?查询下?配对的设备,来?下的设备是是?是

道的是得的。

SetpairedDevices=mBluetoothAdapter.getBondedDevices();

//Iftherearepaireddevices

if(pairedDevices.size()>0){

//Loopthroughpaireddevices

for(BluetoothDevicedevice:pairedDevices){

//AddthenameandaddresstoanarrayadaptertoshowinaListView

mArrayAdapter.add(device.getName()+"\n"+device.getAddress());

}

}

发现?扫描过程”蓝牙设备

动发现过程,调用startDiscovery?”,这是个异fi过程,法马上?返一个布

尔—型,表明发现过程动是否成功。这个发现过程通常包含了12S的扫描查询过程,接

下来是包含了′个˙发现设备的的页扫描来提蓝牙设备的?ˇ。



//CreateaBroadcastReceiverforACTION_FOUND

privatefinalBroadcastReceivermReceiver=newBroadcastReceiver(){

publicvoidonReceive(Contextcontext,Intentintent){

Stringaction=intent.getAction();

//Whendiscoveryfindsadevice

if(BluetoothDevice.ACTION_FOUND.equals(action)){

//GettheBluetoothDeviceobjectfromtheIntent

BluetoothDevicedevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

//AddthenameandaddresstoanarrayadaptertoshowinaListView

mArrayAdapter.add(device.getName()+"\n"+device.getAddress());

}

}

};

//RegistertheBroadcastReceiver

IntentFilterfilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);

registerReceiver(mReceiver,filter);//Don''tforgettounregisterduringonDestroy

为了连接,所从BluetoothDevice对象里面得到的是理,

使能蓝牙设备的可发现?可¨”

IntentdiscoverableIntent=new

Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);

startActivity(discoverableIntent);

:如蓝牙没使能?打开”如直接使能蓝牙可¨,则蓝牙也动打开

如你?一个连接到?程设备,你没必打开可¨。使能可¨仅仅是让

你的应用程序作为服务端Socket,用来接输入连接请。因为?程设备在连接之

必须?发现这个设备。

连接设备

为了在你的应用程序里面让2个设备建立连接,你必须实行服务端和客端连接机制。因为

一个设备必须打开一个serversocket服务端套接ˇ?另一个设备必须这个连接?使

用server设备的理来建立连接”。server和client他之间在?一个RFCOMM通

信通道之间一个连接好了的BluetoothSocket的“?,server和client服务端和客端˙

£为是?建立好了连接。在这个点上,′个设备可以fl得输入输a流,数据传输也可以

开。关于这点在管理连接节介绍,这节如何在2个设备之间连接。

Server设备和client设备各fl得BluetoothSocket用?的式。Server??接收一个

BluetoothSocketserver接一个输入连接请的“?。Client??接收BluetoothSocket

打开一个和server之间的RFCOMM通信通道的“?。

Block?在这里是阻塞的思”

作为服务端连接

你连接2个设备,一个必须作为server服务端,通过¥持打开BluetoothServerSocket,

这个BluetoothServerSocket的目的是为了监听输入连接请并且接了请之`,服务

端得到了一个连接了的BluetoothSocket,从BluetoothServerSocket这里得到了

BluetoothSocket之`,BluetoothServerSocket应˙丢弃,你接多的输入连接

请,你把留o。

下面是建立一个serversocket和acceptaconnection接一个连接请的过程。

1、通过调用listenUsingRfcommWithServiceRecord(String,UUID).得到一个

BluetoothServerSocket,string是你的service服务的?ˇ。系统??动把写入?服务发现

协议?SDP”数据库实例?这个?ˇ是具体的,可以是你的应用程序的?ˇ”到设备上。

?UUID也是数据库实例的一部分并且是与client客端连接的协议。也是说,客

端和设备建立连接,必须承载一个和连接server服务端的一一个一?的

UUID。

2、通过调用accept?”来动监听连接请。这个是阻塞调用法。?在连接˙接了?

·发生了一个异常“才返。一个连接请?˙接,?在一个?程设备发的连接请

的UUID匹配了册的监听serversocket服务套接ˇ的“?。成功的“?,accept?”

?返一个连接了的BluetoothSocket。

3、你继续接输入连接请,否则调用close?”。这个函数?释放serversocket的

所资,''是?关闭?是之accept?”返的?连接了的BluetoothSocket。像

TCP/IP,RFCOMM允许一能建立一个连接通道。

Accept?”函数应在主activity里面调用,因为是一个阻塞调用??阻止在应用程序

里面其他的交互。

Example

Here''sasimplifiedthreadfortheservercomponentthatacceptsincomingconnections:



privateclassAcceptThreadextendsThread{

privatefinalBluetoothServerSocketmmServerSocket;



publicAcceptThread(){

//UseatemporaryobjectthatislaterassignedtommServerSocket,

//becausemmServerSocketisfinal

BluetoothServerSockettmp=null;

try{

//MY_UUIDistheapp''sUUIDstring,alsousedbytheclientcode

tmp=mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME,MY_UUID);

}catch(IOExceptione){}

mmServerSocket=tmp;

}



publicvoidrun(){

BluetoothSocketsocket=null;

//Keeplisteninguntilexceptionoccursorasocketisreturned

while(true){

try{

socket=mmServerSocket.accept();

}catch(IOExceptione){

break;

}

//Ifaconnectionwasaccepted

if(socket!=null){

//Doworktomanagetheconnection(inaseparatethread)

manageConnectedSocket(socket);

mmServerSocket.close();

break;

}

}

}



/Willcancelthelisteningsocket,andcausethethreadtofinish/

publicvoidcancel(){

try{

mmServerSocket.close();

}catch(IOExceptione){}

}

}

作为客端连接

为了连接一个?程设备?个¥持打开服务套接ˇ的设备–serversocket”你必须首

?fl得代表了?程设备的BluetoothDevice的对象。?fl一个BluetoothDevice在查?设备

节?了”`你必须用BluetoothDevice来得到BluetoothSocket和连接。下面

是?的流程

1、用BluetoothDevice得到一个BluetoothSocket,通过调用–

createRfcommSocketToServiceRecord(UUID)这了?连接到BluetoothDevice的

BluetoothSocket蓝牙套接ˇ。这里的UUID必须和server设备通过打开

BluetoothServerSocket?调用listenUsingRfcommWithServiceRecord(String,UUID)”里面用

到的UUID一?。使用一?的UUID仅仅是硬编码ˇ符串到你的应用程序里面,`

在server和client里面引用。

2、调用connect?”来连接。

通过这个法,为了匹配UUID,系统??在?程设备上执行SDP查?。如成功?到的

?程设备??接这个连接,?且在连接中,也?分?这个RFCOMM通信信道?“

connect?”返。这个法也是个阻塞法。如因为某些原因连接失败?·connect?”超

“了?概12S”,这个法?抛a一个异常。因为connect?”是个阻塞调用法,所以

连接程序放在主activity程序之外的一个线程里面。

Example

HereisabasicexampleofathreadthatinitiatesaBluetoothconnection:



privateclassConnectThreadextendsThread{

privatefinalBluetoothSocketmmSocket;

privatefinalBluetoothDevicemmDevice;



publicConnectThread(BluetoothDevicedevice){

//UseatemporaryobjectthatislaterassignedtommSocket,

//becausemmSocketisfinal

BluetoothSockettmp=null;

mmDevice=device;



//GetaBluetoothSockettoconnectwiththegivenBluetoothDevice

try{

//MY_UUIDistheapp''sUUIDstring,alsousedbytheservercode

tmp=device.createRfcommSocketToServiceRecord(MY_UUID);

}catch(IOExceptione){}

mmSocket=tmp;

}



publicvoidrun(){

//Canceldiscoverybecauseitwillslowdowntheconnection

mBluetoothAdapter.cancelDiscovery();



try{

//Connectthedevicethroughthesocket.Thiswillblock

//untilitsucceedsorthrowsanexception

mmSocket.connect();

}catch(IOExceptionconnectException){

//Unabletoconnect;closethesocketandgetout

try{

mmSocket.close();

}catch(IOExceptioncloseException){}

return;

}



//Doworktomanagetheconnection(inaseparatethread)

manageConnectedSocket(mmSocket);

}



/Willcancelanin-progressconnection,andclosethesocket/

publicvoidcancel(){

try{

mmSocket.close();

}catch(IOExceptione){}

}

}

–管理一个连接

你?成功连接好了2个设备?·多的“?,′个设备??一个连接好了的

BluetoothSocket蓝牙套接ˇ。这是蓝牙功能开的“?因为你可以在设之分?数据了。

使用BluetoothSocket蓝牙套接ˇ,分?数据的一流程是?简单的。

1、凭借getInputStream()和getOutputStream()来得到socket的处理流数据的对象

InputStream和OutputStream

2、写数据到流里面通过read(byte[])和–write(byte[]

你应使用一个专门的线程来处理输入输a流。是常重的,因为read(byte[])和–

write(byte[]是阻塞调用法。read(byte[])??阻塞直到流里面东西可以a来。write(byte[]

是通常?阻塞,''是也?因为流控?阻塞。?如?程设备没迅速调用read(byte[])?

·中间缓?满了”所以–你这个线程的主循环应专门从InputStream输入流数据。并且

在这个线程里面应设一个分?的public公法来来写数据到输a流

OutputStream。

Example

Here''sanexampleofhowthismightlook:



privateclassConnectedThreadextendsThread{

privatefinalBluetoothSocketmmSocket;

privatefinalInputStreammmInStream;

privatefinalOutputStreammmOutStream;



publicConnectedThread(BluetoothSocketsocket){

mmSocket=socket;

InputStreamtmpIn=null;

OutputStreamtmpOut=null;



//Gettheinputandoutputstreams,usingtempobjectsbecause

//memberstreamsarefinal

try{

tmpIn=socket.getInputStream();

tmpOut=socket.getOutputStream();

}catch(IOExceptione){}



mmInStream=tmpIn;

mmOutStream=tmpOut;

}



publicvoidrun(){

byte[]buffer=newbyte[1024];//bufferstoreforthestream

intbytes;//bytesreturnedfromread()



//KeeplisteningtotheInputStreamuntilanexceptionoccurs

while(true){

try{

//ReadfromtheInputStream

bytes=mmInStream.read(buffer);

//SendtheobtainedbytestotheUIactivity

mHandler.obtainMessage(MESSAGE_READ,bytes,-1,buffer)

.sendToTarget();

}catch(IOExceptione){

break;

}

}

}



/Callthisfromthemainactivitytosenddatatotheremotedevice/

publicvoidwrite(byte[]bytes){

try{

mmOutStream.write(bytes);

}catch(IOExceptione){}

}



/Callthisfromthemainactivitytoshutdowntheconnection/

publicvoidcancel(){

try{

mmSocket.close();

}catch(IOExceptione){}

}

}

ForademonstrationofusingtheBluetoothAPIs,seetheBluetoothChatsampleapp.关于使用蓝

牙API的演示程序,请查?蓝牙聊天例子程序

献花(0)
+1
(本文系侠客201305首藏)