蓝牙开发的总结

最近在做蓝牙相关的应用,有按照需求写了一个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();



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值