Android蓝⽛socket通信
Android中蓝⽛模块的使⽤
使⽤蓝⽛API,Android应⽤程序能够执⾏以下功能:
扫描其他蓝⽛设备查询本地已经配对的蓝⽛适配器建⽴RFCOMM通道
通过服务发现来连接其他设备
在设备间传输数据
管理多个蓝⽛连接
本⽂介绍如何使⽤Android的蓝⽛API来完成使⽤蓝⽛通信所需要的四项主要任务:设置蓝⽛、查已配对或区域内可⽤的蓝⽛设备、连接设备、设备间传输数据。
1. 使⽤蓝⽛的响应权限
<uses-permission android:name="android.permission.BLUETOOTH" />安卓intent用法
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
2. 配置本机蓝⽛模块
在这⾥⾸先要了解对蓝⽛操作⼀个核⼼类BluetoothAdapter
BluetoothAdapter adapter = DefaultAdapter();
//直接打开系统的蓝⽛设置⾯板
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 0x1);
//直接打开蓝⽛
//关闭蓝⽛
adapter.disable();
//打开本机的蓝⽛发现功能(默认打开120秒,可以将时间最多延长⾄300秒)
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//设置持续时间(最多300秒)
3.搜索蓝⽛设备
使⽤BluetoothAdapter的startDiscovery()⽅法来搜索蓝⽛设备
startDiscovery()⽅法是⼀个异步⽅法,调⽤后会⽴即返回。该⽅法会进⾏对其他蓝⽛设备的搜索,该过程会持续12秒。该⽅法调⽤后,搜索过程实际上是在⼀个System Service中进⾏的,所以可以调⽤cancelDiscovery()⽅法来停⽌搜索(该⽅法可以在未执⾏discovery请求时调⽤)。
请求Discovery后,系统开始搜索蓝⽛设备,在这个过程中,系统会发送以下三个⼴播:
ACTION_DISCOVERY_START:开始搜索
ACTION_DISCOVERY_FINISHED:搜索结束
ACTION_FOUND:到设备,这个Intent中包含两个extra fields:EXTRA_DEVICE和EXTRA_CLASS,分别包含BluetooDevice和BluetoothClass。
我们可以⾃⼰注册相应的BroadcastReceiver来接收响应的⼴播,以便实现某些功能
// 创建⼀个接收ACTION_FOUND⼴播的BroadcastReceiver
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = Action();
// 发现设备
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 从Intent中获取设备对象
BluetoothDevice device = ParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 将设备名称和地址放⼊array adapter,以便在ListView中显⽰
mArrayAdapter.Name() + "\n" + Address());
}
}
};
// 注册BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // 不要忘了之后解除绑定
4. 蓝⽛Socket通信
如果打算建议两个蓝⽛设备之间的连接,则必须实现服务器端与客户端的机制。当两个设备在同⼀个RFCOMM channel下分别拥有⼀个连接的BluetoothSocket,这两个设备才可以说是建⽴了连接。
服务器设备与客户端设备获取BluetoothSocket的途径是不同的。服务器设备是通过accepted⼀个incoming connection来获取的,⽽客户端设备则是通过打开⼀个到服务器的RFCOMM channel来获取的。
服务器端的实现
通过调⽤BluetoothAdapter的listenUsingRfcommWithServiceRecord(String, UUID)⽅法来获取BluetoothServerSocket(UUID⽤于客户端与服务器端之间的配对)
调⽤BluetoothServerSocket的accept()⽅法监听连接请求,如果收到请求,则返回⼀个BluetoothSocket实例(此⽅法为block⽅法,应置于新线程中)
如果不想在accept其他的连接,则调⽤BluetoothServerSocket的close()⽅法释放资源(调⽤该⽅法后,之前获得的BluetoothSocket实例并没有close。但由于RFCOMM⼀个时刻只允许在⼀条channel中有⼀个连接,则⼀般在accept⼀个连接后,便close掉BluetoothServerSocket)
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) { }
}
}
客户端的实现
通过搜索得到服务器端的BluetoothService
调⽤BluetoothService的listenUsingRfcommWithServiceRecord(String, UUID)⽅法获取BluetoothSocket(该UUID应该同于服务器端的UUID)
调⽤BluetoothSocket的connect()⽅法(该⽅法为block⽅法),如果UUID同服务器端的UUID匹配,并且连接被服务器端accept,则connect()⽅法返回
注意:在调⽤connect()⽅法之前,应当确定当前没有搜索设备,否则连接会变得⾮常慢并且容易失败
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 = ateRfcommSocketToServiceRecord(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
} 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) { }
}
}
连接管理(数据通信)
分别通过BluetoothSocket的getInputStream()和getOutputStream()⽅法获取InputStream和OutputStream
使⽤read(bytes[])和write(bytes[])⽅法分别进⾏读写操作
注意:read(bytes[])⽅法会⼀直block,知道从流中读取到信息,⽽write(bytes[])⽅法并不是经常的block(⽐如在另⼀设备没有及时read或者中间缓冲区已满的情况下,write⽅法会block)
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 = InputStream();
tmpOut = OutputStream();
} 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 = ad(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) { }
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论