Android开发 蓝牙通讯 (二)实战
上一篇文章中我们的开发思路是使用两个手机,一个作为服务端另一个作为客户端
首先封装BluetoothController工具类
public class BluetoothController {
private BluetoothAdapter mAdapter;
private static final UUID MY_UUID= UUID.fromString(
"00001101-0000-1000-8000-00805F9B34FB");//蓝牙串口服务
public BluetoothController(){
mAdapter = BluetoothAdapter.getDefaultAdapter();//若mAdapter==null,则不支持蓝牙
if(mAdapter==null){
ToastUtil.MsgLong("设备不支持蓝牙!");
}else {
ToastUtil.MsgLong("设备支持蓝牙!");
}
}
/**
* 获取蓝牙的状态
*/
public boolean getBluetoothStatus() {
if (mAdapter != null) {
return mAdapter.isEnabled();
}
return false;
}
/**
* 打开蓝牙
* @param activity
* @param requestCode
*/
public void turnOnBluetooth(Activity activity, int requestCode) {
if (mAdapter != null && !mAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
activity.startActivityForResult(intent, requestCode);
}
}
/**
* 蓝牙是否打开
*/
public boolean isEnabled() {
if (mAdapter != null ) {
return mAdapter.isEnabled();
}
return false;
}
/**
* 关闭蓝牙
*/
public void turnOffBluetooth() {
if (mAdapter != null && mAdapter.isEnabled()) {
mAdapter.disable();
}
}
public void ensureDiscoverable(){
//设备可见
if (mAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,3000);
startActivity(discoverableIntent);
}
}
/**扫描设备*/
public void startDiscovery(){
if (mAdapter != null && mAdapter.