为了方便大家学习,工程已打包上传,http://download.csdn.net/detail/devintt/8029477
安卓设备一般都配备了蓝牙模块,我们可以使用蓝牙模块和一些外设进行数据交换,并且在安卓设备上处理和显示出来。
蓝牙编程:主要使用到系统提供的BroadcastReceiver使得我们可以对蓝牙模块接收到的数据进行广播接收。
蓝牙操作第一步就是检查蓝牙状态和打开蓝牙设备
/**
* 打开buletooth
*/
private void openBluetoothSettings() {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!bluetoothAdapter.isEnabled()) { // 蓝牙未开启,则开启蓝牙
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
receiver = new BluetoothReceiver();
registerReceiver(receiver, filter);
Toast.makeText(MainActivity.this, "open buletooth success",
Toast.LENGTH_LONG).show();
bluetoothAdapter.startDiscovery();
Toast.makeText(MainActivity.this, "searching", Toast.LENGTH_LONG)
.show();
}
}
再注册蓝牙广播接收BroadcastReceiver
private class BluetoothReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("TAG", "onReceive");
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Toast.makeText(MainActivity.this, "ACTION_FOUND",
// Toast.LENGTH_LONG).show();
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (isLock(device)) {
Toast.makeText(MainActivity.this, "isLock",
Toast.LENGTH_LONG).show();
devices.add(device.getName() + " : " + device.getAddress());
Log.e("TAG", "isLock");
} else {
devices.add(device.getName());
Log.e("TAG", "device.getName()");
}
deviceList.add(device);
}
showDevices();
}
}
以下两个方法可以不使用
用于锁定指定的蓝牙设备
private boolean isLock(BluetoothDevice device) {
boolean isLockName = (device.getName()).equals(lockName);
boolean isSingleDevice = devices.indexOf(device.getName()) == -1;
return isLockName && isSingleDevice;
}
用于被其他蓝牙设备可搜索到
private void showDevices() {
Log.e("TAG", "showDevices");
// Toast.makeText(MainActivity.this, "showDevices",
// Toast.LENGTH_LONG).show();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, devices);
listView.setAdapter(arrayAdapter);
}
接下来新建一个类,用于蓝牙连接、发送、接收和运行线程,将接收到的数据用masssage发送到UI进程,更新UI。
这是用于连接蓝牙设备,由于通信是耗时操作,这里为了不堵塞UI线程,新建了一个线程。
public void connect(final String message) {
Thread threadConnect = new Thread(new Runnable() {
public void run() {
BluetoothSocket tmp = null;
Method method;
try {
method = device.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
tmp = (BluetoothSocket) method.invoke(device, 1);
Log.d("TAG", device.getName()+" : "+device.getAddress());
} catch (Exception e) {
setState(CONNECT_FAILED);
Log.e("TAG", "fail creat: " + e.toString());
}
socket = tmp;
try {
socket.connect();
isConnect = true;
Log.d("TAG", "socket connected");
setState(CONNECT_SUCCESS);
} catch (Exception e) {
setState(CONNECT_FAILED);
isConnect = false;
Log.e("TAG", "fail connect: " + e.toString());
}
}
});
threadConnect.start();
}
这是用于发送信息,使用OutputStream以流输出,单片机可以直接接收。注意的是,安卓蓝牙波特率9800,1位停止位,无校验,这是不能修改的,也是默认的。
public void chatOUT(String msg) {
if (isConnect) {
Log.e("TAG", "chatOUT...");
try {
OutputStream outStream = socket.getOutputStream();
Log.d("DATA", "output: " + msg.length());
//outStream.write(getHexBytes(msg));
outStream.write(msg.getBytes());
} catch (IOException e) {
setState(WRITE_FAILED);
Log.e("TAG", "fail send: " + e.toString());
}
// }
}
}
蓝牙接收是耗时操作,用一个线程进行长链接,以BufferedInputStream流读取,将接收到的数据用masssage发送到UI进程,更新UI。
public void chatIN() {
Thread threadChat = new Thread(new Runnable() {
public void run() {
if (isConnect) {
Log.e("TAG", "chatIN...");
try {
BufferedInputStream inputStream =new BufferedInputStream(socket.getInputStream());
while (true) {
try {
char buff = (char) inputStream.read();
Message msg = handler.obtainMessage();
msg.what = DATA;
msg.obj = data;
handler.sendMessage(msg);
data = "";
// Log.e("DATA", "input: " + buff);
} catch (IOException e) {
setState(READ_FAILED);
Log.e("TAG", "fail get: " + e.toString());
break;
}
}
} catch (IOException e) {
setState(WRITE_FAILED);
Log.e("TAG", e.toString());
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
Log.e("TAG", "fail close: " + e.toString());
}
}
}
});
threadChat.start();
}
为了方便大家学习,工程已打包上传,http://download.csdn.net/detail/devintt/8029477