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


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

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

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

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


[java] view plain copy
  1. //获取蓝牙适配器
  2. BluetoothAdapterbtAdapter=BlueToothService.getInstance().getBtAdapter();
  3. //开启蓝牙
  4. if(!btAdapter.isEnabled()){
  5. IntentenableIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  6. startActivityForResult(enableIntent,ConstantsUtil.ENABLE_BLUETOOTH);
  7. }


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

[java] view plain copy
  1. @Override
  2. protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
  3. switch(requestCode){
  4. caseConstantsUtil.ENABLE_BLUETOOTH:
  5. if(resultCode==Activity.RESULT_OK){
  6. bluetoothProcess(PSystem.isServer);
  7. }else{
  8. finish();
  9. }
  10. }
  11. }
  12. publicvoidbluetoothProcess(booleanisServer){
  13. BlueToothService.getInstance().setsHandler(mHandler);
  14. if(isServer){
  15. //如果是蓝牙服务器,则需要开启发现服务,并启动蓝牙服务器
  16. if(btAdapter.getScanMode()!=BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
  17. IntentdiscoverableIntent=newIntent(
  18. BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  19. discoverableIntent.putExtra(
  20. BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,180);
  21. startActivity(discoverableIntent);
  22. }
  23. BlueToothService.getInstance().start();
  24. }else{
  25. //如果是蓝牙客户端则扫描周围可用的蓝牙设备
  26. blueToothNames=newArrayList<String>();
  27. blutToothDevices=newArrayList<BluetoothDevice>();
  28. //添加过滤器,并注册广播,用于监听蓝牙发现信息
  29. IntentFilterfilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);
  30. this.registerReceiver(mReceiver,filter);
  31. filter=newIntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  32. this.registerReceiver(mReceiver,filter);
  33. //开始扫描
  34. doDiscovery();
  35. }
  36. }
  37. publicvoiddoDiscovery(){
  38. if(btAdapter.isDiscovering()){
  39. btAdapter.cancelDiscovery();
  40. }
  41. btAdapter.startDiscovery();
  42. }


3 蓝牙广播接收器

[java] view plain copy
  1. privatefinalBroadcastReceivermReceiver=newBroadcastReceiver(){
  2. @Override
  3. publicvoidonReceive(Contextcontext,Intentintent){
  4. Stringaction=intent.getAction();
  5. if(BluetoothDevice.ACTION_FOUND.equals(action)){
  6. BluetoothDevicedevice=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. }elseif(BluetoothAdapter.ACTION_DISCOVERY_FINISHED
  13. .equals(action)){
  14. btAdapter.cancelDiscovery();
  15. TestActivity.this.unregisterReceiver(this);
  16. }
  17. }
  18. };


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

蓝牙服务器监听代码:

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

客户端连接代码:

[java] view plain copy
  1. publicvoidconnect(BluetoothDevicedevice){
  2. try{
  3. btAdapter.cancelDiscovery();
  4. btSocket=device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
  5. changeState(ConstantsUtil.BT_STATE_CONNECTING);
  6. btSocket.connect();
  7. }catch(IOExceptione){
  8. }
  9. changeState(ConstantsUtil.BT_STATE_CONNECTED);
  10. }


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

[java] view plain copy
  1. classConnectedThreadextendsThread{
  2. privatefinalBluetoothSocketmmSocket;
  3. privatefinalInputStreammmInStream;
  4. privatefinalOutputStreammmOutStream;
  5. publicConnectedThread(BluetoothSocketsocket){
  6. mmSocket=socket;
  7. InputStreamtmpIn=null;
  8. OutputStreamtmpOut=null;
  9. try{
  10. tmpIn=socket.getInputStream();
  11. tmpOut=socket.getOutputStream();
  12. }catch(IOExceptione){
  13. Log.e(TAG,"tempsocketsnotcreated",e);
  14. }
  15. mmInStream=tmpIn;
  16. mmOutStream=tmpOut;
  17. }
  18. publicvoidrun(){
  19. byte[]buffer=newbyte[1024];
  20. intbytes;
  21. while(true){
  22. try{
  23. bytes=mmInStream.read(buffer);
  24. if(transHandler!=null){
  25. //通知数据传输处理器
  26. transHandler.sendMessage(transHandler.obtainMessage(ConstantsUtil.BT_READ,bytes,-1,buffer));
  27. }
  28. }catch(IOExceptione){
  29. Log.e(TAG,"disconnected",e);
  30. break;
  31. }
  32. }
  33. }
  34. publicvoidwrite(byte[]buffer){
  35. try{
  36. mmOutStream.write(buffer);
  37. }catch(IOExceptione){
  38. Log.e(TAG,"Exceptionduringwrite",e);
  39. }
  40. }
  41. publicvoidcancel(){
  42. try{
  43. mmSocket.close();
  44. }catch(IOExceptione){
  45. Log.e(TAG,"close()ofconnectsocketfailed",e);
  46. }
  47. }
  48. }

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐