使用HC-06无线蓝牙串口透传模块。对于其它的蓝牙设备本文相同适用。
<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(); } } }
//创建连接的进程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(); } }