Android 蓝牙开发详述

来源:互联网 发布:java const 编辑:程序博客网 时间:2024/05/21 22:53

http://blog.csdn.net/einarzhang/article/details/6943861

在AndroidSDK sample中给出了一个蓝牙聊天的示例代码,本文只是略作修改变成一个简单的服务器和客户端模式的应用,以适应在游戏开发中一对一关联的数据传输。

由于游戏中的蓝牙设置在新线程中发生,所以采用Handler的方式将蓝牙的状态以及读取信息传输给显示Activity。

1 开启蓝牙,包括xml中的配置: 

[html] view plaincopy
  1. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />  
  2. <uses-permission android:name="android.permission.BLUETOOTH" />  


[java] view plaincopy
  1.  //获取蓝牙适配器  
  2. BluetoothAdapter btAdapter = BlueToothService.getInstance().getBtAdapter();  
  3. //开启蓝牙  
  4. if (!btAdapter.isEnabled()) {  
  5.   
  6.          Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  
  7.   
  8.          startActivityForResult(enableIntent, ConstantsUtil.ENABLE_BLUETOOTH);  
  9.   
  10. }  


 2 在当前Activity中获取蓝牙开启结果,并根据具体情况对蓝牙进行处理

[java] view plaincopy
  1. @Override  
  2.   
  3. protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  4.   
  5.        switch (requestCode) {  
  6.   
  7.        case ConstantsUtil.ENABLE_BLUETOOTH:  
  8.   
  9.            if (resultCode == Activity.RESULT_OK) {  
  10.   
  11.               bluetoothProcess(PSystem.isServer);  
  12.   
  13.            } else {  
  14.   
  15.               finish();  
  16.   
  17.            }  
  18.   
  19.        }  
  20.   
  21.     }  
  22.   
  23. public void bluetoothProcess(boolean isServer) {  
  24.     BlueToothService.getInstance().setsHandler(mHandler);  
  25.     if (isServer) {  
  26.         //如果是蓝牙服务器,则需要开启发现服务,并启动蓝牙服务器  
  27.         if(btAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {  
  28.             Intent discoverableIntent = new Intent(  
  29.                 BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);  
  30.             discoverableIntent.putExtra(  
  31.                 BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 180);  
  32.             startActivity(discoverableIntent);  
  33.         }  
  34.         BlueToothService.getInstance().start();  
  35.     } else {  
  36.         //如果是蓝牙客户端则扫描周围可用的蓝牙设备  
  37.         blueToothNames = new ArrayList<String>();  
  38.         blutToothDevices = new ArrayList<BluetoothDevice>();  
  39.         //添加过滤器,并注册广播,用于监听蓝牙发现信息  
  40.         IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);  
  41.         this.registerReceiver(mReceiver, filter);  
  42.         filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);  
  43.         this.registerReceiver(mReceiver, filter);  
  44.         //开始扫描  
  45.         doDiscovery();  
  46.     }  
  47. }  
  48. public void doDiscovery() {  
  49.     if (btAdapter.isDiscovering()) {  
  50.     btAdapter.cancelDiscovery();  
  51.     }  
  52.     btAdapter.startDiscovery();  
  53.  }  


 

3 蓝牙广播接收器

[java] view plaincopy
  1. private final BroadcastReceiver mReceiver = new BroadcastReceiver() {  
  2.         @Override  
  3.         public void onReceive(Context context, Intent intent) {  
  4.             String action = intent.getAction();  
  5.             if (BluetoothDevice.ACTION_FOUND.equals(action)) {  
  6.                 BluetoothDevice device = intent  
  7.                         .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
  8.                 if(device.getName() != null && !device.getName().trim().equals("")) {  
  9.                     blueToothNames.add(device.getName());  
  10.                     blutToothDevices.add(device);  
  11.                 }  
  12.             } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED  
  13.                     .equals(action)) {  
  14.                 btAdapter.cancelDiscovery();  
  15.                 TestActivity.this.unregisterReceiver(this);  
  16.             }  
  17.         }  
  18.     };  


4 以上是蓝牙基本配置和发现。现在进行蓝牙监听和连接:

蓝牙服务器监听代码:

[java] view plaincopy
  1. public void start() {  
  2.         BluetoothServerSocket serverSocket = null;  
  3.         try {  
  4.             serverSocket = btAdapter.listenUsingRfcommWithServiceRecord("JumpForMeApp", MY_UUID_SECURE);  
  5.             changeState(ConstantsUtil.BT_STATE_LISTEN);  
  6.             btSocket = serverSocket.accept();  
  7.         } catch (IOException e) {  
  8.         } finally {  
  9.             try {  
  10.                 serverSocket.close();  
  11.             } catch (IOException e) {  
  12.             }  
  13.         }   
  14.         if(btSocket != null) {  
  15.             changeState(ConstantsUtil.BT_STATE_CONNECTED);  
  16.         }  
  17.     }  

客户端连接代码:

[java] view plaincopy
  1. public void connect(BluetoothDevice device) {  
  2.         try {  
  3.             btAdapter.cancelDiscovery();  
  4.             btSocket = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);  
  5.             changeState(ConstantsUtil.BT_STATE_CONNECTING);  
  6.             btSocket.connect();  
  7.         } catch (IOException e) {  
  8.         }  
  9.         changeState(ConstantsUtil.BT_STATE_CONNECTED);  
  10.     }  


5 利用蓝牙进行消息传递,建立新的线程来处理读写操作(见BluetoothChat Sample中的ConnectedThread):
 

[java] view plaincopy
  1. class ConnectedThread extends Thread {  
  2.         private final BluetoothSocket mmSocket;  
  3.         private final InputStream mmInStream;  
  4.         private final OutputStream mmOutStream;  
  5.   
  6.         public ConnectedThread(BluetoothSocket socket) {  
  7.             mmSocket = socket;  
  8.             InputStream tmpIn = null;  
  9.             OutputStream tmpOut = null;  
  10.             try {  
  11.                 tmpIn = socket.getInputStream();  
  12.                 tmpOut = socket.getOutputStream();  
  13.             } catch (IOException e) {  
  14.                 Log.e(TAG, "temp sockets not created", e);  
  15.             }  
  16.             mmInStream = tmpIn;  
  17.             mmOutStream = tmpOut;  
  18.         }  
  19.   
  20.         public void run() {  
  21.             byte[] buffer = new byte[1024];  
  22.             int bytes;  
  23.             while (true) {  
  24.                 try {  
  25.                     bytes = mmInStream.read(buffer);  
  26.                     if(transHandler != null) {  
  27.                         //通知数据传输处理器  
  28.                         transHandler.sendMessage(transHandler.obtainMessage(ConstantsUtil.BT_READ, bytes, -1, buffer));  
  29.                     }  
  30.                 } catch (IOException e) {  
  31.                     Log.e(TAG, "disconnected", e);  
  32.                     break;  
  33.                 }  
  34.             }  
  35.         }  
  36.   
  37.         public void write(byte[] buffer) {  
  38.             try {  
  39.                 mmOutStream.write(buffer);  
  40.             } catch (IOException e) {  
  41.                 Log.e(TAG, "Exception during write", e);  
  42.             }  
  43.         }  
  44.   
  45.         public void cancel() {  
  46.             try {  
  47.                 mmSocket.close();  
  48.             } catch (IOException e) {  
  49.                 Log.e(TAG, "close() of connect socket failed", e);  
  50.             }  
  51.         }  
  52.     }  

原创粉丝点击