Android蓝牙开发

来源:互联网 发布:淘宝上靠谱的法国代购 编辑:程序博客网 时间:2024/05/20 16:32

Android蓝牙开发

最近做蓝牙小车,需要Android端来控制小车的运动,以此文记录开发过程。使用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(){@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubString 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();}}}};

广播返回不同设备及其所处的状态,getAction()方法用于获取状态,BOND_BONDED表示是已经配对的状态。(注意配对和连接是两个完全不同的概念,配对成功并不是连接成功,仅仅配对成功不能够发送信息)

当然是用广播机制要注意注册广播:
 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是可行的,其他的设备未测试
想使用时只需创建一个clientThread对象,然后执行其run()方法即可,如下:

//创建连接的进程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();          }                   }






此处的UUID用于连接HC-06是可行的,其他的设备未测试
2 0
原创粉丝点击