蓝牙Socket编程
实现蓝牙Socket服务器
蓝牙Server端就是通过线程来注册一个具有名称和唯一识别的UUID号的BluetoothServerSocket, 然后就一直监听Client端(BluetoothSocket)的请求,并对这些请求做出相应的处理。
// 注册蓝牙Server
BleutoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
BluetoothServerSocket serverSocket = bluetooth.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM, UUID.fromString(“xxxx-xxxx-xxxx-xxxx-xxxx”));
参数PROTOCOL_SCHEME_RFCOMM是一个String类型的常量,表示蓝牙Server的名称,而UUID.fromString()表示蓝牙Server的唯一标识UUID。
在Client连接到Server时需要使用该UUID号。
// 接收Client的连接请求
BluetoothSocket socket = serverSocket.accept();
// 处理请求内容
if(socket != null) { }
// 关闭蓝牙Server
serverSocket.close();
示例完整代码
public class ServerSocketActivity extends ListActivity {
// 一些常量,表示Server的名称
public static final String PROTOCOL_SCHEME_L2CAP = “btl2cap”;
public static final String PROTOCOL_SCHEME_RFCOMM = “btspp”;
public static final String PROTOCOL_SCHEME_BT_OBEX = “btobex”;
public static final String PROTOCOL_SCHEME_TCP_OBEX = “tcpobex”;
private Handler mHandler = new Handler();
private BleutoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
private BluetoothServerSocket serverSocket;
private Thread serverWorker = new Thread(){
public void run(){
listen();
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayouParams.FLAG_BLUE_BEHIND, WindowManager.LayouParams.FLAG_BLUE_BEHIND);
setContentView(R.layout.server_socket);
if(!bluetooth.isEnabled()){
finish();
return;
}
serverWorker.start();
}
protected void onDestroy() {
super.onDestroy();
shutdownServer();
}
protected void finalize() throws Throwable {
super.finalize();
shutdownServer();
}
private void shutdownServer() {
// Why does it create a thread below ?
new Thread() {
public void run() {
serverWorker.interrupt();
if(serverSocket!=null) {
try {
serverSocket.close();
} catch(IOException ex) { }
}
}
}.start();
}
public void onButtonClicked(View view) {
shutdownServer();
}
protected void listen() {
try {
serverSocket = bluetooth.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM, UUID.fromString(“xxxx-xxxx-xxxx-xxxx-xxxx”));
// Client连接列表
final List<String> lines = new ArrayList<String>();
mHandler.post(new Runnable(){
public void run(){
lines.add(“server started …”);
ArrayAdaper<String> adpater = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, lines);
setListAdapter(adapter);
}
});
BluetoothSocket socket = serverSocket.accept();
// 处理请求内容
if(socket!=null){
InputStream is = socket.getInputStream();
int read = –1;
final byte[] bytes = new byte[2048];
while((read = is.read(bytes)) > -1) {
final int count = read;
mHandler.post(new Runnable() {
public void run() {
StringBuilder builder = new StringBuilder();
// …
lines.add(builder.toString());
ArrayAdaper<String> adpater = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, lines);
setListAdapter(adapter);
}
});
} // while
} // if
} catch (IOException ex) { }
} // listen()
}
public class ClientSocketActivity extends Activity {
private static final int REQUEST_DISCOVERY = 0x1;
private Handler mHandler = new Handler();
private BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayouParams.FLAG_BLUE_BEHIND, WindowManager.LayouParams.FLAG_BLUE_BEHIND);
setContentView(R.layout.client_socket);
if(!bluetooth.isEnabled()){
finish();
return;
}
Intent it = new Intent(mContext, DiscoveryActivity.class);
Toast.makeText(mContext, “select device to connect.”, Toast.LENGTH_SHORT).show();
startActivityForResult(it, REQUEST_DISCOVERY);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode != REQUEST_DISCOVERY || resultCode != RESULT_OK) {
return;
}
final BluetoothDevice device = data.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
new Thread(){
public void run() {
connect(device);
}
}.start();
}
protected void connect(BluetoothDevice device) {
BluetoothSocket socket = null;
try {
// socket = device.createRfcommSocketToServiceRecord(BluetoothProtocols.OBEX_OBJECT_PUSH_PROTOCOL_UUID);
socket = device.createRfcommSocketToServiceRecord(UUID.fromString(“xxxx-xxxx-xxxx-xxxx”));
socket.connect();
} catch (IOException ex) {
} finally {
socket.close();
}
}
}