80,351
社区成员
发帖
与我相关
我的任务
分享
//得到蓝牙信息
List<Beacon> beacons = intent.getParcelableArrayListExtra("beacon");
Log.i(TAG, "onReceive: " + beacons.size());
private void sendMessage() {
SharedPreferences sp = MyApplication.getContext().getSharedPreferences("bluetooth", Context.MODE_PRIVATE);
Log.e(TAG, "蓝牙地址:" + sp.getString("bluetooth_address", ""));
if (!"".equals(sp.getString("bluetooth_address", ""))) {
// 获取到蓝牙默认的适配器
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//通过地址获取到该设备
selectDevice = mBluetoothAdapter.getRemoteDevice(sp.getString("bluetooth_address", ""));
// 这里需要try catch一下,以防异常抛出
try {
// 判断客户端接口是否为空
if (clientSocket == null) {
// 获取到客户端接口
clientSocket = selectDevice
.createRfcommSocketToServiceRecord(UUID.fromString(sp.getString("bluetooth_uuid", "")));
// 向服务端发送连接
clientSocket.connect();
// 获取到输出流,向外写数据
os = clientSocket.getOutputStream();
}
// 判断是否拿到输出流
if (os != null) {
// 需要发送的信息
String text = "成功发送信息";
// 以utf-8的格式发送出去
os.write(text.getBytes("UTF-8"));
}
// 吐司一下,告诉用户发送成功
Log.e(TAG, "发送信息成功,请查收");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 如果发生异常则告诉用户发送失败
Log.e(TAG, "发送信息失败");
}
}
}