<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(); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/cassiepython/article/details/47374155