最近在做蓝牙相关的应用,有按照需求写了一个demo,做下记录,以便后续的查验吧:
1:mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();先得到一个蓝牙设备的句柄
2: if (!mBluetoothAdapter.enable()) {
Log.e(TAG, "ysfeagle#onStart#enable#in");
Intent enableintent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableintent, REQUEST_ENABLE_BT);
}
先去判断是否enable,如果非的话,启动一个intent去enable它。
3:然后选择scan,则调用
Intent serverIntent = new Intent(this, BtDeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
在BtDeviceListActivity的Activity里面会得到当前配对的蓝牙设备的一个列表,然后选择某一个设备。
mBtAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
4;在onActivityResult里面
case REQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
//if (mChatService != null)
// mChatService.stop();
String address = data.getExtras().getString(
BtDeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = mBluetoothAdapter
.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device);
5:mChatService是BluetoothService这个class的实例,在connect的时候,如果是该设备是server的话,则
device.createRfcommSocketToServiceRecord(MY_UUID);
mAdapter.cancelDiscovery();
mmSocket.connect();
当然这个是在一个thread里面进行的
6:如果是一个client的话,
mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
socket = mmServerSocket.accept();
connected(socket, socket.getRemoteDevice());
同样这个必须得在另外的thread里面
7:connected之后,
InputStream tmpIn = null;
OutputStream tmpOut = null;
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BtmainActivity.MESSAGE_READ, bytes,
-1, buffer).sendToTarget();
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(BtmainActivity.MESSAGE_WRITE, -1, -1,
buffer).sendToTarget();