一:手机蓝牙功能有且打开
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
deviceAdapter = new BluetoothDevicesAdapter(BlueToothActivity.this);
deviceAdapter.addDevices(list_devices);
listView.setAdapter(deviceAdapter);
if (bluetoothAdapter != null) {
if (!bluetoothAdapter.isEnabled()) {// 是否打开
Intent intent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);// 蓝牙可发现
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
300);// 可发现300秒
startActivity(intent);
}
} else {
Toast.makeText(BlueToothActivity.this, "该设备无蓝牙模块!",
Toast.LENGTH_LONG).show();
}
二:开启广播注册
private void registerBlueToothReciver() {
// TODO Auto-generated method stub
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);// 扫描完毕
filter.addAction(BluetoothDevice.ACTION_FOUND);// 发现
filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);// 远程设备状态发生改变
registerReceiver(MyReciver, filter);
}
三:扫描蓝牙设备
1:扫描蓝牙设备
private void ScanBlueTooth() {
// TODO Auto-generated method stub
if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
if (bluetoothAdapter.isDiscovering()) {
Toast.makeText(BlueToothActivity.this, "正在扫描请稍等!",
Toast.LENGTH_LONG).show();
return;
} else {
list_devices.clear();
deviceAdapter.notifyDataSetChanged();
bluetoothAdapter.startDiscovery();
}
}
}
2:扫描已绑定的蓝牙设备
private void ScanBondBlueTooth() {
// TODO Auto-generated method stub
Set<BluetoothDevice> bondedDevices = bluetoothAdapter
.getBondedDevices();
for (BluetoothDevice device : bondedDevices) {
if (!list_devices.contains(device)) {
list_devices.add(device);
}
}
deviceAdapter.notifyDataSetChanged();
}
四:单条点击连接匹配蓝牙
public void ConnectBlueToothServer(BluetoothDevice bluetoothDevice) {
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
// 获取远程蓝牙
BluetoothDevice remoteDevice = bluetoothAdapter
.getRemoteDevice(bluetoothDevice.getAddress());
int bondState = bluetoothDevice.getBondState();
switch (bondState) {
case BluetoothDevice.BOND_BONDING:
BlueToothActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(BlueToothActivity.this, "正在匹配请稍等!",
Toast.LENGTH_LONG).show();
}
});
break;
case BluetoothDevice.BOND_NONE:// 未配对
try {
Method method = BluetoothDevice.class.getMethod("createBond",
null);
Object invoke = method.invoke(remoteDevice, null);
if ((Boolean) invoke) {
// 配对成功后,用uuid建立socket连接
bluetoothSocket = remoteDevice
.createRfcommSocketToServiceRecord(UUID
.fromString(PUBLIC_UUID));
bluetoothSocket.connect();
if (bluetoothSocket.isConnected()) {
/*
* InputStream inputStream =
* bluetoothSocket.getInputStream(); byte[] b = new
* byte[8*1024]; inputStream.read(b);
* Toast.makeText(BlueToothClientDemo.this,b.toString(),
* Toast.LENGTH_SHORT).show(); Logger.e(TAG,
* b.toString());
*/
new ReadThread().start();
}
}
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
break;
case BluetoothDevice.BOND_BONDED:// 配对成功的
try {
bluetoothSocket = remoteDevice
.createRfcommSocketToServiceRecord(UUID
.fromString(PUBLIC_UUID));
while(!bluetoothSocket.isConnected()){
bluetoothSocket.connect();
}
if (bluetoothSocket.isConnected()) {
BlueToothActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(BlueToothActivity.this, "请求成功,请上传数据!",
Toast.LENGTH_SHORT).show();
dialog = EpProgressDialog.show(BlueToothActivity.this, null, "正在接收处理数据");
}
});
Thread.sleep(500);
new ReadThread().start();
}
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
BlueToothActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(BlueToothActivity.this, "请求连接超时,请重新连接!",
Toast.LENGTH_SHORT).show();
if (dialog != null) {
dialog.dismiss();
}
}
});
}
break;
default:
break;
}
}
五:BuletoothSocket中获取流读取数据
private class ReadThread extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
InputStream inputStream = null;
ByteArrayOutputStream baos = null;
String message = "";
try {
inputStream = bluetoothSocket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = 0;
/**
* inputStream是服务器也就是仪器的流,read方法是个堵塞的方法,会一直读取仪器的数据,造成堵塞。
*/
boolean isReaded = false;
while (!isReaded) {
len = inputStream.read(b);
byte[] buf_data = new byte[len];
for (int i = 0; i < len; i++) {
buf_data[i] = b[i];
}
// final String s = new String(buf_data);
final String s = bytesToHexFun3(buf_data);
message = message + s;
/**
* 头是68以及0129长度,结尾是4A16基本固定
*/
int lens = 0;
if(message.length()>=126){
String zcd = message.substring(2, 6);
lens = Integer.parseInt(zcd, 16)*2+10;
}
if(message.length() == lens && message.length() != 0){
isReaded = true;
inputStream.close();
bluetoothSocket.close();
}
// 没有数据,起始104(0x68),长度为0(两字节0,0),结束符是22(0x16)
}
List<String> list = getBean(message);
for (int i = 0; i < list.size(); i++) {
ResolveMessage(list.get(i),dy);
if(i == list.size()-1){
isFinish = true;
BlueToothActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(BlueToothActivity.this, "数据接收完毕!",
Toast.LENGTH_SHORT).show();
if (dialog != null) {
dialog.dismiss();
}
}
});
}
}
BlueToothActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if(isFinish){
Intent intent = new Intent(BlueToothActivity.this,Table_zldzActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("LIST", list_zldz);
intent.putExtra("DATA", bundle);
setResult(100, intent);
finish();
}
}
});
} catch (Exception e) {//java.io.IOException: socket closed
// TODO: handle exception
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (baos != null) {
try {
baos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
BlueToothActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(BlueToothActivity.this,
"仪器已关闭蓝牙,请重新连接!", Toast.LENGTH_SHORT).show();
if (dialog != null) {
dialog.dismiss();
}
}
});
}
}
}