Android蓝牙开发
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />private BluetoothAdapter adapter = null;//用于获取蓝牙适配器
private BluetoothDevice mBtDevice = null;//用于获取蓝牙设备
private BluetoothSocket mBtSocket = null;//用于建立通信获取蓝牙适配器:
adapter = BluetoothAdapter.getDefaultAdapter();打开蓝牙:
boolean enabled = adapter.enable();
if(!enabled){
adapter.enable();
}搜索设备:
adapter.startDiscovery();private BroadcastReceiver blueRevever = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_FOUND)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(device.getBondState()!=BluetoothDevice.BOND_BONDED){
//获取未配对的设备名称和MAC地址
//根据搜索到的蓝牙设备的MAC地址,得到该设备
mBtDevice = adapter.getRemoteDevice(device.getAddress());
//如果设备名称是指定的设备则给出提示
if(device.getName().equals("HC-06")){
Toast.makeText(MainActivity.this,device.getName(),Toast.LENGTH_LONG).show();
}
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Toast.makeText(MainActivity.this,"检测完毕",Toast.LENGTH_LONG).show();
}
}}}; IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(blueRevever, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(blueRevever, filter);
连接设备:
private class clientThread extends Thread{
public void run(){
try {
//取消搜索设备的动作,否则接下来的设备连接会失败
adapter.cancelDiscovery();
//根据device获取socket
mBtSocket = mBtDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
//连接socket
mBtSocket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this,"连接失败!!!!!!!!!",Toast.LENGTH_LONG).show();
}
}
}此处的UUID用于连接HC-06是可行的,其他的设备未测试
//创建连接的进程
Thread mBtClientConnectThread = new clientThread();
//开启进程
mBtClientConnectThread.start();
发送信息:
public void sendMessageHandle(String msg)
{
if (mBtSocket == null)
{
Toast.makeText(MainActivity.this,"没有连接!!",Toast.LENGTH_LONG).show();
return;
}
try {
OutputStream os = mBtSocket.getOutputStream();
os.write(msg.getBytes()); //发送出去的值为:msg
Toast.makeText(MainActivity.this,"发送成功!!",Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this,"发送失败!!!!!!!!!",Toast.LENGTH_LONG).show();
}
}
1510



被折叠的 条评论
为什么被折叠?



