android 蓝牙通信编程

公司项目涉及蓝牙通信,所以就简单的学了学,下面是自己参考了一些资料后的总结,希望对大家有帮助。

以下是开发中的几个关键步骤:

1,首先开启蓝牙

2,搜索可用设备

3,创建蓝牙socket,获取输入输出流

4,读取和写入数据

5,断开连接关闭蓝牙


下面是一个蓝牙聊天demo

效果图:



2015-09-20更新(主要对蓝牙按照功能进行封装,增加程序可读性,可移植)

在使用蓝牙是 BluetoothAdapter 对蓝牙开启,关闭,获取设备列表,发现设备,搜索等核心功能

下面对它进行封装:

[java]  view plain copy
  1. package com.xiaoyu.bluetooth;  
  2.   
  3.   
  4. import java.util.ArrayList;  
  5. import java.util.Iterator;  
  6. import java.util.List;  
  7. import java.util.Set;  
  8.   
  9. import android.app.Activity;  
  10. import android.app.AlertDialog;  
  11. import android.bluetooth.BluetoothAdapter;  
  12. import android.bluetooth.BluetoothDevice;  
  13. import android.content.BroadcastReceiver;  
  14. import android.content.Context;  
  15. import android.content.DialogInterface;  
  16. import android.content.Intent;  
  17. import android.content.IntentFilter;  
  18.   
  19. public class BTManage {  
  20.   
  21. //  private List<BTItem> mListDeviceBT=null;  
  22.     private BluetoothAdapter mBtAdapter =null;  
  23.     private static BTManage mag=null;  
  24.       
  25.     private BTManage(){  
  26. //      mListDeviceBT=new ArrayList<BTItem>();  
  27.         mBtAdapter=BluetoothAdapter.getDefaultAdapter();  
  28.     }  
  29.       
  30.     public static BTManage getInstance(){  
  31.         if(null==mag)  
  32.             mag=new BTManage();  
  33.         return mag;  
  34.     }  
  35.       
  36.     private StatusBlueTooth blueStatusLis=null;  
  37.     public void setBlueListner(StatusBlueTooth blueLis){  
  38.         this.blueStatusLis=blueLis;  
  39.     }  
  40.       
  41.     public BluetoothAdapter getBtAdapter(){  
  42.         return this.mBtAdapter;  
  43.     }  
  44.       
  45.     public void openBluetooth(Activity activity){  
  46.         if(null==mBtAdapter){   Device does not support Bluetooth   
  47.             AlertDialog.Builder dialog = new AlertDialog.Builder(activity);    
  48.             dialog.setTitle("No bluetooth devices");    
  49.             dialog.setMessage("Your equipment does not support bluetooth, please change device");    
  50.                 
  51.             dialog.setNegativeButton("cancel",    
  52.                     new DialogInterface.OnClickListener() {    
  53.                         @Override    
  54.                         public void onClick(DialogInterface dialog, int which) {    
  55.                                 
  56.                         }    
  57.                     });    
  58.             dialog.show();    
  59.             return;  
  60.         }  
  61.         // If BT is not on, request that it be enabled.  
  62.         if (!mBtAdapter.isEnabled()) {  
  63.             /*Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
  64.             activity.startActivityForResult(enableIntent, 3);*/  
  65.             mBtAdapter.enable();  
  66.         }  
  67.     }  
  68.       
  69.     public void closeBluetooth(){  
  70.         if(mBtAdapter.isEnabled())  
  71.             mBtAdapter.disable();  
  72.     }  
  73.       
  74.     public boolean isDiscovering(){  
  75.         return mBtAdapter.isDiscovering();  
  76.     }  
  77.       
  78.     public void scanDevice(){  
  79. //      mListDeviceBT.clear();  
  80.         if(!mBtAdapter.isDiscovering())  
  81.             mBtAdapter.startDiscovery();  
  82.     }  
  83.       
  84.     public void cancelScanDevice(){  
  85.         if(mBtAdapter.isDiscovering())  
  86.             mBtAdapter.cancelDiscovery();  
  87.     }  
  88.       
  89.     public void registerBluetoothReceiver(Context mcontext){  
  90.          // Register for broadcasts when start bluetooth search  
  91.         IntentFilter startSearchFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);  
  92.         mcontext.registerReceiver(mBlueToothReceiver, startSearchFilter);  
  93.          // Register for broadcasts when a device is discovered  
  94.         IntentFilter discoveryFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);  
  95.         mcontext.registerReceiver(mBlueToothReceiver, discoveryFilter);  
  96.         // Register for broadcasts when discovery has finished  
  97.         IntentFilter foundFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);  
  98.         mcontext.registerReceiver(mBlueToothReceiver, foundFilter);  
  99.     }  
  100.       
  101.     public void unregisterBluetooth(Context mcontext){  
  102.         cancelScanDevice();  
  103.         mcontext.unregisterReceiver(mBlueToothReceiver);  
  104.     }  
  105.       
  106.     public List<BTItem> getPairBluetoothItem(){  
  107.         List<BTItem> mBTitemList=null;  
  108.         // Get a set of currently paired devices  
  109.         Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();  
  110.         Iterator<BluetoothDevice> it=pairedDevices.iterator();  
  111.         while(it.hasNext()){  
  112.             if(mBTitemList==null)  
  113.                 mBTitemList=new ArrayList<BTItem>();  
  114.               
  115.             BluetoothDevice device=it.next();  
  116.             BTItem item=new BTItem();  
  117.             item.setBuletoothName(device.getName());  
  118.             item.setBluetoothAddress(device.getAddress());  
  119.             item.setBluetoothType(BluetoothDevice.BOND_BONDED);  
  120.             mBTitemList.add(item);  
  121.         }  
  122.         return mBTitemList;  
  123.     }  
  124.       
  125.       
  126.      private final BroadcastReceiver mBlueToothReceiver = new BroadcastReceiver() {  
  127.             @Override  
  128.             public void onReceive(Context context, Intent intent) {  
  129.                 String action = intent.getAction();  
  130.                 if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {  
  131.                     if(blueStatusLis!=null)  
  132.                         blueStatusLis.BTDeviceSearchStatus(StatusBlueTooth.SEARCH_START);  
  133.                 }  
  134.                 else if (BluetoothDevice.ACTION_FOUND.equals(action)){  
  135.                     // When discovery finds a device  
  136.                     // Get the BluetoothDevice object from the Intent  
  137.                     BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
  138.                     // If it's already paired, skip it, because it's been listed already  
  139.                     if (device.getBondState() != BluetoothDevice.BOND_BONDED) {  
  140.                         BTItem item=new BTItem();  
  141.                         item.setBuletoothName(device.getName());  
  142.                         item.setBluetoothAddress(device.getAddress());  
  143.                         item.setBluetoothType(device.getBondState());  
  144.                           
  145.                         if(blueStatusLis!=null)  
  146.                             blueStatusLis.BTSearchFindItem(item);  
  147.       //                mListDeviceBT.add(item);  
  148.                     }  
  149.                 }   
  150.                 else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){  
  151.                      // When discovery is finished, change the Activity title  
  152.                     if(blueStatusLis!=null)  
  153.                         blueStatusLis.BTDeviceSearchStatus(StatusBlueTooth.SEARCH_END);  
  154.                 }  
  155.             }  
  156.         };    
  157.           
  158.           
  159. }  

蓝牙开发和socket一致,分为server,client

server功能类封装:

[java]  view plain copy
  1. package com.xiaoyu.bluetooth;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.EOFException;  
  6. import java.io.IOException;  
  7. import java.util.UUID;  
  8.   
  9. import com.xiaoyu.utils.ThreadPool;  
  10.   
  11. import android.bluetooth.BluetoothAdapter;  
  12. import android.bluetooth.BluetoothServerSocket;  
  13. import android.bluetooth.BluetoothSocket;  
  14. import android.os.Handler;  
  15. import android.os.Message;  
  16.   
  17. public class BTServer {  
  18.   
  19.     /* 一些常量,代表服务器的名称 */  
  20.     public static final String PROTOCOL_SCHEME_L2CAP = "btl2cap";  
  21.     public static final String PROTOCOL_SCHEME_RFCOMM = "btspp";  
  22.     public static final String PROTOCOL_SCHEME_BT_OBEX = "btgoep";  
  23.     public static final String PROTOCOL_SCHEME_TCP_OBEX = "tcpobex";  
  24.       
  25.     private BluetoothServerSocket btServerSocket = null;  
  26.     private BluetoothSocket btsocket = null;  
  27.     private BluetoothAdapter mBtAdapter =null;  
  28.     private BufferedInputStream bis=null;  
  29.     private BufferedOutputStream bos=null;  
  30.   
  31.     private Handler detectedHandler=null;  
  32.       
  33.     public BTServer(BluetoothAdapter mBtAdapter,Handler detectedHandler){  
  34.         this.mBtAdapter=mBtAdapter;  
  35.         this.detectedHandler=detectedHandler;  
  36.     }  
  37.       
  38.     public void startBTServer() {  
  39.         ThreadPool.getInstance().excuteTask(new Runnable() {  
  40.             public void run() {  
  41.                 try {  
  42.                     btServerSocket = mBtAdapter.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM,  
  43.                     UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));  
  44.                       
  45.                     Message msg = new Message();    
  46.                     msg.obj = "请稍候,正在等待客户端的连接...";    
  47.                     msg.what = 0;    
  48.                     detectedHandler.sendMessage(msg);    
  49.                       
  50.                     btsocket=btServerSocket.accept();  
  51.                     Message msg2 = new Message();    
  52.                     String info = "客户端已经连接上!可以发送信息。";    
  53.                     msg2.obj = info;    
  54.                     msg.what = 0;    
  55.                     detectedHandler.sendMessage(msg2);    
  56.                        
  57.                     receiverMessageTask();  
  58.                 } catch(EOFException e){  
  59.                     Message msg = new Message();    
  60.                     msg.obj = "client has close!";    
  61.                     msg.what = 1;    
  62.                     detectedHandler.sendMessage(msg);  
  63.                 }catch (IOException e) {  
  64.                     e.printStackTrace();  
  65.                     Message msg = new Message();    
  66.                     msg.obj = "receiver message error! please make client try again connect!";    
  67.                     msg.what = 1;    
  68.                     detectedHandler.sendMessage(msg);  
  69.                 }  
  70.             }  
  71.         });  
  72.     }  
  73.       
  74.     private void receiverMessageTask(){  
  75.         ThreadPool.getInstance().excuteTask(new Runnable() {  
  76.             public void run() {  
  77.                 byte[] buffer = new byte[2048];  
  78.                 int totalRead;  
  79.                 /*InputStream input = null; 
  80.                 OutputStream output=null;*/  
  81.                 try {  
  82.                     bis=new BufferedInputStream(btsocket.getInputStream());  
  83.                     bos=new BufferedOutputStream(btsocket.getOutputStream());  
  84.                 } catch (IOException e) {  
  85.                     e.printStackTrace();  
  86.                 }  
  87.                   
  88.                 try {  
  89.                 //  ByteArrayOutputStream arrayOutput=null;  
  90.                     while((totalRead = bis.read(buffer)) > 0 ){  
  91.                 //       arrayOutput=new ByteArrayOutputStream();  
  92.                         String txt = new String(buffer, 0, totalRead, "UTF-8");   
  93.                         Message msg = new Message();    
  94.                         msg.obj = txt;    
  95.                         msg.what = 1;    
  96.                         detectedHandler.sendMessage(msg);    
  97.                     }  
  98.                 } catch (IOException e) {  
  99.                     e.printStackTrace();  
  100.                 }  
  101.             }  
  102.         });  
  103.     }  
  104.       
  105.     public boolean sendmsg(String msg){  
  106.         boolean result=false;  
  107.         if(null==btsocket||bos==null)  
  108.             return false;  
  109.         try {  
  110.             bos.write(msg.getBytes());  
  111.             bos.flush();  
  112.             result=true;  
  113.         } catch (IOException e) {  
  114.             e.printStackTrace();  
  115.         }  
  116.         return result;  
  117.     }  
  118.       
  119.     public void closeBTServer(){  
  120.         try{  
  121.         if(bis!=null)  
  122.             bis.close();  
  123.         if(bos!=null)  
  124.             bos.close();  
  125.         if(btServerSocket!=null)  
  126.             btServerSocket.close();  
  127.         if(btsocket!=null)  
  128.             btsocket.close();  
  129.         }catch(IOException e){  
  130.             e.printStackTrace();  
  131.         }  
  132.     }  
  133.       
  134. }  

client功能封装:

[java]  view plain copy
  1. package com.xiaoyu.bluetooth;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.EOFException;  
  6. import java.io.IOException;  
  7. import java.util.UUID;  
  8.   
  9. import android.bluetooth.BluetoothAdapter;  
  10. import android.bluetooth.BluetoothDevice;  
  11. import android.bluetooth.BluetoothSocket;  
  12. import android.os.Handler;  
  13. import android.os.Message;  
  14. import android.util.Log;  
  15.   
  16. import com.xiaoyu.utils.ThreadPool;  
  17.   
  18. public class BTClient {  
  19.   
  20.     final String Tag=getClass().getSimpleName();  
  21.     private BluetoothSocket btsocket = null;  
  22.     private BluetoothDevice btdevice = null;  
  23.     private BufferedInputStream bis=null;  
  24.     private BufferedOutputStream bos=null;  
  25.     private BluetoothAdapter mBtAdapter =null;  
  26.       
  27.     private Handler detectedHandler=null;  
  28.       
  29.     public BTClient(BluetoothAdapter mBtAdapter,Handler detectedHandler){  
  30.         this.mBtAdapter=mBtAdapter;  
  31.         this.detectedHandler=detectedHandler;  
  32.     }  
  33.       
  34.     public void connectBTServer(String address){  
  35.         //check address is correct  
  36.         if(BluetoothAdapter.checkBluetoothAddress(address)){  
  37.             btdevice = mBtAdapter.getRemoteDevice(address);   
  38.                 ThreadPool.getInstance().excuteTask(new Runnable() {  
  39.                     public void run() {  
  40.                         try {  
  41.                             btsocket = btdevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));  
  42.                               
  43.                             Message msg2 = new Message();    
  44.                             msg2.obj = "请稍候,正在连接服务器:"+BluetoothMsg.BlueToothAddress;    
  45.                             msg2.what = 0;    
  46.                             detectedHandler.sendMessage(msg2);    
  47.                                 
  48.                             btsocket.connect();   
  49.                             Message msg = new Message();    
  50.                             msg.obj = "已经连接上服务端!可以发送信息。";    
  51.                             msg.what = 0;    
  52.                             detectedHandler.sendMessage(msg);    
  53.                             receiverMessageTask();  
  54.                         } catch (IOException e) {  
  55.                             e.printStackTrace();  
  56.                             Log.e(Tag, e.getMessage());  
  57.                               
  58.                              Message msg = new Message();    
  59.                              msg.obj = "连接服务端异常!请检查服务器是否正常,断开连接重新试一试。";    
  60.                              msg.what = 0;    
  61.                             detectedHandler.sendMessage(msg);  
  62.                         }  
  63.                           
  64.                     }  
  65.                 });  
  66.             }  
  67.     }  
  68.       
  69.     private void receiverMessageTask(){  
  70.         ThreadPool.getInstance().excuteTask(new Runnable() {  
  71.             public void run() {  
  72.                 byte[] buffer = new byte[2048];  
  73.                 int totalRead;  
  74.                 /*InputStream input = null; 
  75.                 OutputStream output=null;*/  
  76.                 try {  
  77.                     bis=new BufferedInputStream(btsocket.getInputStream());  
  78.                     bos=new BufferedOutputStream(btsocket.getOutputStream());  
  79.                 } catch (IOException e) {  
  80.                     e.printStackTrace();  
  81.                 }  
  82.                   
  83.                 try {  
  84.                 //  ByteArrayOutputStream arrayOutput=null;  
  85.                     while((totalRead = bis.read(buffer)) > 0 ){  
  86.                 //       arrayOutput=new ByteArrayOutputStream();  
  87.                         String txt = new String(buffer, 0, totalRead, "UTF-8");   
  88.                         Message msg = new Message();    
  89.                         msg.obj = "Receiver: "+txt;    
  90.                         msg.what = 1;    
  91.                         detectedHandler.sendMessage(msg);    
  92.                     }  
  93.                 } catch(EOFException e){  
  94.                     Message msg = new Message();    
  95.                     msg.obj = "server has close!";    
  96.                     msg.what = 1;    
  97.                     detectedHandler.sendMessage(msg);  
  98.                 }catch (IOException e) {  
  99.                     e.printStackTrace();  
  100.                     Message msg = new Message();    
  101.                     msg.obj = "receiver message error! make sure server is ok,and try again connect!";    
  102.                     msg.what = 1;    
  103.                     detectedHandler.sendMessage(msg);  
  104.                 }  
  105.             }  
  106.         });  
  107.     }  
  108.       
  109.     public boolean sendmsg(String msg){  
  110.         boolean result=false;  
  111.         if(null==btsocket||bos==null)  
  112.             return false;  
  113.         try {  
  114.             bos.write(msg.getBytes());  
  115.             bos.flush();  
  116.             result=true;  
  117.         } catch (IOException e) {  
  118.             e.printStackTrace();  
  119.         }  
  120.         return result;  
  121.     }  
  122.       
  123.     public void closeBTClient(){  
  124.         try{  
  125.             if(bis!=null)  
  126.                 bis.close();  
  127.             if(bos!=null)  
  128.                 bos.close();  
  129.             if(btsocket!=null)  
  130.                 btsocket.close();  
  131.         }catch(IOException e){  
  132.             e.printStackTrace();  
  133.         }  
  134.     }  
  135.       
  136. }  

聊天界面,使用上面分装好的类,处理信息

[java]  view plain copy
  1. package com.xiaoyu.communication;  
  2.   
  3.   
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import android.app.Activity;  
  8. import android.content.Context;  
  9. import android.content.Intent;  
  10. import android.os.Bundle;  
  11. import android.os.Handler;  
  12. import android.os.Message;  
  13. import android.text.TextUtils;  
  14. import android.view.Menu;  
  15. import android.view.View;  
  16. import android.view.View.OnClickListener;  
  17. import android.view.inputmethod.InputMethodManager;  
  18. import android.widget.ArrayAdapter;  
  19. import android.widget.Button;  
  20. import android.widget.EditText;  
  21. import android.widget.ListView;  
  22. import android.widget.RadioGroup;  
  23. import android.widget.RadioGroup.OnCheckedChangeListener;  
  24. import android.widget.Toast;  
  25.   
  26. import com.xiaoyu.bluetooth.BTClient;  
  27. import com.xiaoyu.bluetooth.BTManage;  
  28. import com.xiaoyu.bluetooth.BTServer;  
  29. import com.xiaoyu.bluetooth.BluetoothMsg;  
  30.   
  31. public class BTChatActivity extends Activity {  
  32.   
  33.     private ListView mListView;    
  34.     private Button sendButton;    
  35.     private Button disconnectButton;    
  36.     private EditText editMsgView;    
  37.     private ArrayAdapter<String> mAdapter;    
  38.     private List<String> msgList=new ArrayList<String>();  
  39.       
  40.     private BTClient client;  
  41.     private BTServer server;  
  42.       
  43.     @Override  
  44.     protected void onCreate(Bundle savedInstanceState) {  
  45.         super.onCreate(savedInstanceState);  
  46.         setContentView(R.layout.bt_chat);  
  47.         initView();  
  48.                   
  49.     }  
  50.   
  51.     private Handler detectedHandler = new Handler(){  
  52.         public void handleMessage(android.os.Message msg) {  
  53.             msgList.add(msg.obj.toString());    
  54.              mAdapter.notifyDataSetChanged();    
  55.              mListView.setSelection(msgList.size() - 1);    
  56.         };  
  57.     };  
  58.       
  59.      private void initView() {              
  60.            
  61.          mAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, msgList);    
  62.          mListView = (ListView) findViewById(R.id.list);    
  63.          mListView.setAdapter(mAdapter);    
  64.          mListView.setFastScrollEnabled(true);    
  65.          editMsgView= (EditText)findViewById(R.id.MessageText);      
  66.          editMsgView.clearFocus();    
  67.            
  68.          RadioGroup group = (RadioGroup)this.findViewById(R.id.radioGroup);  
  69.          group.setOnCheckedChangeListener(new OnCheckedChangeListener() {  
  70. //             @Override  
  71. //             public void onCheckedChanged(RadioGroup arg0, int arg1) {  
  72. //                 int radioId = arg0.getCheckedRadioButtonId();  
  73. //                  
  74. //             }  
  75.              @Override  
  76.             public void onCheckedChanged(RadioGroup group, int checkedId) {  
  77.                 switch(checkedId){  
  78.                 case R.id.radioNone:  
  79.                     BluetoothMsg.serviceOrCilent = BluetoothMsg.ServerOrCilent.NONE;  
  80.                     if(null!=client){  
  81.                         client.closeBTClient();  
  82.                         client=null;  
  83.                     }  
  84.                     if(null!=server){  
  85.                         server.closeBTServer();  
  86.                         server=null;  
  87.                     }  
  88.                     break;  
  89.                 case R.id.radioClient:  
  90.                     BluetoothMsg.serviceOrCilent = BluetoothMsg.ServerOrCilent.CILENT;  
  91.                     Intent it=new Intent(getApplicationContext(),BTDeviceActivity.class);    
  92.                     startActivityForResult(it, 100);  
  93.                     break;  
  94.                 case R.id.radioServer:  
  95.                     BluetoothMsg.serviceOrCilent = BluetoothMsg.ServerOrCilent.SERVICE;  
  96.                     initConnecter();  
  97.                     break;  
  98.                 }  
  99.             }  
  100.          });  
  101.            
  102.          sendButton= (Button)findViewById(R.id.btn_msg_send);    
  103.          sendButton.setOnClickListener(new OnClickListener() {    
  104.              @Override    
  105.              public void onClick(View arg0) {    
  106.                  
  107.                  String msgText =editMsgView.getText().toString();    
  108.                  if (msgText.length()>0) {    
  109.                      if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.CILENT){    
  110.                          if(null==client)  
  111.                              return;  
  112.                          if(client.sendmsg(msgText)){  
  113.                              Message msg = new Message();    
  114.                              msg.obj = "send: "+msgText;    
  115.                              msg.what = 1;    
  116.                              detectedHandler.sendMessage(msg);   
  117.                          }else{  
  118.                              Message msg = new Message();    
  119.                              msg.obj = "send fail!! ";    
  120.                              msg.what = 1;    
  121.                              detectedHandler.sendMessage(msg);   
  122.                          }  
  123.                       }    
  124.                       else if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.SERVICE) {    
  125.                           if(null==server)  
  126.                              return;  
  127.                           if(server.sendmsg(msgText)){  
  128.                              Message msg = new Message();    
  129.                               msg.obj = "send: "+msgText;    
  130.                               msg.what = 1;    
  131.                               detectedHandler.sendMessage(msg);   
  132.                           }else{  
  133.                              Message msg = new Message();    
  134.                               msg.obj = "send fail!! ";    
  135.                               msg.what = 1;    
  136.                               detectedHandler.sendMessage(msg);   
  137.                           }  
  138.                       }      
  139.                      editMsgView.setText("");    
  140. //                     editMsgView.clearFocus();    
  141. //                     //close InputMethodManager    
  142. //                     InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);     
  143. //                     imm.hideSoftInputFromWindow(editMsgView.getWindowToken(), 0);    
  144.                  }else{    
  145.                      Toast.makeText(getApplicationContext(), "发送内容不能为空!", Toast.LENGTH_SHORT).show();  
  146.                  }  
  147.              }    
  148.          });    
  149.              
  150.          disconnectButton= (Button)findViewById(R.id.btn_disconnect);    
  151.          disconnectButton.setOnClickListener(new OnClickListener() {    
  152.              @Override    
  153.              public void onClick(View arg0) {    
  154.                  if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.CILENT){    
  155.                      if(null==client)  
  156.                          return;  
  157.                     client.closeBTClient();  
  158.                  }    
  159.                  else if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.SERVICE) {   
  160.                      if(null==server)  
  161.                          return;  
  162.                      server.closeBTServer();  
  163.                  }    
  164.                  BluetoothMsg.isOpen = false;    
  165.                  BluetoothMsg.serviceOrCilent=BluetoothMsg.ServerOrCilent.NONE;    
  166.                  Toast.makeText(getApplicationContext(), "已断开连接!", Toast.LENGTH_SHORT).show();    
  167.              }    
  168.          });         
  169.      }        
  170.        
  171.      @Override  
  172.     protected void onResume() {  
  173.         super.onResume();  
  174.           
  175.         if (BluetoothMsg.isOpen) {  
  176.             Toast.makeText(getApplicationContext(), "连接已经打开,可以通信。如果要再建立连接,请先断开!",  
  177.                     Toast.LENGTH_SHORT).show();  
  178.         }  
  179.     }  
  180.        
  181.      @Override  
  182.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  183.         super.onActivityResult(requestCode, resultCode, data);  
  184.         if(requestCode==100){  
  185.             //从设备列表返回  
  186.             initConnecter();  
  187.         }  
  188.     }  
  189.        
  190.     private void initConnecter(){  
  191.         if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.CILENT) {  
  192.             String address = BluetoothMsg.BlueToothAddress;  
  193.             if (!TextUtils.isEmpty(address)) {  
  194.                 if(null==client)  
  195.                     client=new BTClient(BTManage.getInstance().getBtAdapter(), detectedHandler);  
  196.                 client.connectBTServer(address);  
  197.                 BluetoothMsg.isOpen = true;  
  198.             } else {  
  199.                 Toast.makeText(getApplicationContext(), "address is empty please choose server address !",  
  200.                         Toast.LENGTH_SHORT).show();  
  201.             }  
  202.         } else if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.SERVICE) {  
  203.             if(null==server)  
  204.                 server=new BTServer(BTManage.getInstance().getBtAdapter(), detectedHandler);  
  205.             server.startBTServer();  
  206.             BluetoothMsg.isOpen = true;  
  207.         }  
  208.     }  
  209.       
  210.     @Override  
  211.     public boolean onCreateOptionsMenu(Menu menu) {  
  212.         // Inflate the menu; this adds items to the action bar if it is present.  
  213.         getMenuInflater().inflate(R.menu.main, menu);  
  214.         return true;  
  215.     }  
  216.   
  217. }  



client搜索设备列表,连接选择server界面:

[java]  view plain copy
  1. package com.xiaoyu.communication;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import android.app.Activity;  
  7. import android.app.AlertDialog;  
  8. import android.content.DialogInterface;  
  9. import android.content.Intent;  
  10. import android.os.Bundle;  
  11. import android.view.View;  
  12. import android.widget.AdapterView;  
  13. import android.widget.AdapterView.OnItemClickListener;  
  14. import android.widget.ArrayAdapter;  
  15. import android.widget.Button;  
  16. import android.widget.ListView;  
  17.   
  18. import com.xiaoyu.bluetooth.BTItem;  
  19. import com.xiaoyu.bluetooth.BTManage;  
  20. import com.xiaoyu.bluetooth.BluetoothMsg;  
  21. import com.xiaoyu.bluetooth.StatusBlueTooth;  
  22.   
  23. public class BTDeviceActivity extends Activity implements OnItemClickListener  
  24.                     ,View.OnClickListener ,StatusBlueTooth{    
  25.   
  26. //  private List<BTItem> mListDeviceBT=new ArrayList<BTItem>();  
  27.     private ListView deviceListview;    
  28.     private Button btserch;    
  29.     private BTDeviceAdapter adapter;    
  30.     private boolean hasregister=false;    
  31.       
  32.     @Override  
  33.     protected void onCreate(Bundle savedInstanceState) {  
  34.         super.onCreate(savedInstanceState);  
  35.         setContentView(R.layout.finddevice);  
  36.         setView();  
  37.           
  38.         BTManage.getInstance().setBlueListner(this);  
  39.     }  
  40.   
  41.      private void setView(){    
  42.             deviceListview=(ListView)findViewById(R.id.devicelist);    
  43.             deviceListview.setOnItemClickListener(this);  
  44.             adapter=new BTDeviceAdapter(getApplicationContext());    
  45.             deviceListview.setAdapter(adapter);    
  46.             deviceListview.setOnItemClickListener(this);    
  47.             btserch=(Button)findViewById(R.id.start_seach);    
  48.             btserch.setOnClickListener(this);   
  49.     }    
  50.        
  51.     @Override  
  52.     protected void onStart() {  
  53.         super.onStart();  
  54.         //注册蓝牙接收广播    
  55.         if(!hasregister){    
  56.             hasregister=true;    
  57.             BTManage.getInstance().registerBluetoothReceiver(getApplicationContext());  
  58.         }     
  59.     }  
  60.       
  61.     @Override  
  62.     protected void onResume() {  
  63.         // TODO Auto-generated method stub  
  64.         super.onResume();  
  65.     }  
  66.   
  67.     @Override  
  68.     protected void onPause() {  
  69.         // TODO Auto-generated method stub  
  70.         super.onPause();  
  71.     }  
  72.       
  73.     @Override  
  74.     protected void onStop() {  
  75.         super.onStop();  
  76.         if(hasregister){    
  77.             hasregister=false;    
  78.             BTManage.getInstance().unregisterBluetooth(getApplicationContext());    
  79.         }    
  80.     }  
  81.       
  82.     @Override  
  83.     protected void onDestroy() {  
  84.         super.onDestroy();  
  85.           
  86.     }  
  87.   
  88.     @Override  
  89.     public void onItemClick(AdapterView<?> parent, View view, int position,  
  90.             long id) {  
  91.           
  92.         final BTItem item=(BTItem)adapter.getItem(position);  
  93.           
  94.             
  95.         AlertDialog.Builder dialog = new AlertDialog.Builder(this);// 定义一个弹出框对象    
  96.         dialog.setTitle("Confirmed connecting device");    
  97.         dialog.setMessage(item.getBuletoothName());    
  98.         dialog.setPositiveButton("connect",    
  99.                 new DialogInterface.OnClickListener() {    
  100.                     @Override    
  101.                     public void onClick(DialogInterface dialog, int which) {    
  102.                     //  btserch.setText("repeat search");  
  103.                         BTManage.getInstance().cancelScanDevice();  
  104.                         BluetoothMsg.BlueToothAddress=item.getBluetoothAddress();   
  105.                           
  106.                         if(BluetoothMsg.lastblueToothAddress!=BluetoothMsg.BlueToothAddress){    
  107.                             BluetoothMsg.lastblueToothAddress=BluetoothMsg.BlueToothAddress;    
  108.                         }    
  109.                        setResult(100);  
  110.                        finish();  
  111.                     }    
  112.                 });    
  113.         dialog.setNegativeButton("cancel",    
  114.                 new DialogInterface.OnClickListener() {    
  115.                     @Override    
  116.                     public void onClick(DialogInterface dialog, int which) {    
  117.                         BluetoothMsg.BlueToothAddress = null;    
  118.                     }    
  119.                 });    
  120.         dialog.show();    
  121.     }  
  122.   
  123.     @Override  
  124.     public void onClick(View v) {  
  125.         BTManage.getInstance().openBluetooth(this);  
  126.           
  127.         if(BTManage.getInstance().isDiscovering()){    
  128.             BTManage.getInstance().cancelScanDevice();    
  129.             btserch.setText("start search");    
  130.         }else{    
  131.             BTManage.getInstance().scanDevice();   
  132.             btserch.setText("stop search");    
  133.         }    
  134.     }  
  135.   
  136.     @Override  
  137.     public void BTDeviceSearchStatus(int resultCode) {  
  138.         switch(resultCode){  
  139.         case StatusBlueTooth.SEARCH_START:  
  140.             adapter.clearData();  
  141.             adapter.addDataModel(BTManage.getInstance().getPairBluetoothItem());  
  142.             break;  
  143.         case StatusBlueTooth.SEARCH_END:  
  144.             break;  
  145.         }  
  146.     }  
  147.   
  148.     @Override  
  149.     public void BTSearchFindItem(BTItem item) {  
  150.         adapter.addDataModel(item);  
  151.     }  
  152.   
  153.     @Override  
  154.     public void BTConnectStatus(int result) {  
  155.           
  156.     }  
  157.   
  158. }  

搜索列表adapter:

[java]  view plain copy
  1. package com.xiaoyu.communication;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import android.content.Context;  
  7. import android.view.LayoutInflater;  
  8. import android.view.View;  
  9. import android.view.ViewGroup;  
  10. import android.widget.BaseAdapter;  
  11. import android.widget.TextView;  
  12.   
  13. import com.xiaoyu.bluetooth.BTItem;  
  14.   
  15. public class BTDeviceAdapter extends BaseAdapter{  
  16.   
  17.       
  18.     private List<BTItem> mListItem=new ArrayList<BTItem>();;  
  19.     private Context mcontext=null;  
  20.     private LayoutInflater mInflater=null;  
  21.       
  22.     public BTDeviceAdapter(Context context){  
  23.         this.mcontext=context;  
  24.     //  this.mListItem=mListItem;  
  25.         this.mInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  26.           
  27.     }  
  28.       
  29.     void clearData(){  
  30.         mListItem.clear();  
  31.     }  
  32.       
  33.     void addDataModel(List<BTItem> itemList){  
  34.         if(itemList==null || itemList.size()==0)  
  35.             return;  
  36.         mListItem.addAll(itemList);  
  37.         notifyDataSetChanged();  
  38.     }  
  39.     void addDataModel(BTItem item){  
  40.         mListItem.add(item);  
  41.         notifyDataSetChanged();  
  42.     }  
  43.       
  44.     @Override  
  45.     public int getCount() {  
  46.           
  47.         return mListItem.size();  
  48.     }  
  49.   
  50.     @Override  
  51.     public Object getItem(int position) {  
  52.           
  53.         return mListItem.get(position);  
  54.     }  
  55.   
  56.     @Override  
  57.     public long getItemId(int position) {  
  58.           
  59.         return position;  
  60.     }  
  61.   
  62.     @Override  
  63.     public View getView(int position, View convertView, ViewGroup parent) {  
  64.         ViewHolder holder=null;  
  65.           
  66.         if(convertView==null){  
  67.             holder=new ViewHolder();  
  68.             convertView = mInflater.inflate(R.layout.device_item_row, null);  
  69.             holder.tv=(TextView)convertView.findViewById(R.id.itemText);  
  70.             convertView.setTag(holder);  
  71.         }else{  
  72.             holder=(ViewHolder)convertView.getTag();  
  73.         }  
  74.           
  75.           
  76.         holder.tv.setText(mListItem.get(position).getBuletoothName());  
  77.         return convertView;  
  78.     }  
  79.   
  80.       
  81.      class ViewHolder{  
  82.          TextView tv;  
  83.      }  
  84.   
  85. }  

列表model:

[java]  view plain copy
  1. package com.xiaoyu.bluetooth;  
  2.   
  3. public class BTItem {  
  4.   
  5.     private String buletoothName=null;  
  6.     private String bluetoothAddress=null;  
  7.     private int bluetoothType=-1;  
  8.       
  9.     public String getBuletoothName() {  
  10.         return buletoothName;  
  11.     }  
  12.     public void setBuletoothName(String buletoothName) {  
  13.         this.buletoothName = buletoothName;  
  14.     }  
  15.     public String getBluetoothAddress() {  
  16.         return bluetoothAddress;  
  17.     }  
  18.     public void setBluetoothAddress(String bluetoothAddress) {  
  19.         this.bluetoothAddress = bluetoothAddress;  
  20.     }  
  21.     public int getBluetoothType() {  
  22.         return bluetoothType;  
  23.     }  
  24.     public void setBluetoothType(int bluetoothType) {  
  25.         this.bluetoothType = bluetoothType;  
  26.     }  
  27.       
  28.       
  29. }  

使用到的辅助类:

[java]  view plain copy
  1. package com.xiaoyu.bluetooth;  
  2.   
  3. public class BluetoothMsg {  
  4.   
  5.     public enum ServerOrCilent{    
  6.         NONE,    
  7.         SERVICE,    
  8.         CILENT    
  9.     };    
  10.     //蓝牙连接方式    
  11.     public static ServerOrCilent serviceOrCilent = ServerOrCilent.NONE;    
  12.     //连接蓝牙地址    
  13.     public static String BlueToothAddress = null,lastblueToothAddress=null;    
  14.     //通信线程是否开启    
  15.     public static boolean isOpen = false;   
  16. }  

[java]  view plain copy
  1. package com.xiaoyu.bluetooth;  
  2.   
  3. public interface StatusBlueTooth {  
  4.   
  5.     final static int SEARCH_START=110;  
  6.     final static int SEARCH_END=112;  
  7.       
  8.     final static int serverCreateSuccess=211;  
  9.     final static int serverCreateFail=212;  
  10.     final static int clientCreateSuccess=221;  
  11.     final static int clientCreateFail=222;  
  12.     final static int connectLose=231;  
  13.       
  14.     void BTDeviceSearchStatus(int resultCode);  
  15.     void BTSearchFindItem(BTItem item);  
  16.     void BTConnectStatus(int result);  
  17.       
  18. }  

[java]  view plain copy
  1. package com.xiaoyu.utils;  
  2.   
  3. import java.util.concurrent.LinkedBlockingQueue;  
  4. import java.util.concurrent.ThreadFactory;  
  5. import java.util.concurrent.ThreadPoolExecutor;  
  6. import java.util.concurrent.TimeUnit;  
  7. import java.util.concurrent.atomic.AtomicBoolean;  
  8. import java.util.concurrent.atomic.AtomicInteger;  
  9.   
  10. public class ThreadPool {  
  11.   
  12.      private AtomicBoolean mStopped = new AtomicBoolean(Boolean.FALSE);    
  13.      private ThreadPoolExecutor mQueue;    
  14.      private final int coreSize=2;  
  15.      private final int maxSize=10;  
  16.      private final int timeOut=2;  
  17.      private static ThreadPool pool=null;  
  18.         
  19.         private ThreadPool() {    
  20.             mQueue = new ThreadPoolExecutor(coreSize, maxSize, timeOut, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), sThreadFactory);    
  21.         //    mQueue.allowCoreThreadTimeOut(true);    
  22.         }    
  23.           
  24.       public static ThreadPool getInstance(){  
  25.           if(null==pool)  
  26.               pool=new ThreadPool();  
  27.           return pool;  
  28.       }  
  29.           
  30.         public void excuteTask(Runnable run) {    
  31.             mQueue.execute(run);    
  32.         }    
  33.         
  34.         public void closeThreadPool() {    
  35.             if (!mStopped.get()) {    
  36.                 mQueue.shutdownNow();    
  37.                 mStopped.set(Boolean.TRUE);    
  38.             }    
  39.         }    
  40.         
  41.         private static final ThreadFactory sThreadFactory = new ThreadFactory() {    
  42.             private final AtomicInteger mCount = new AtomicInteger(1);    
  43.         
  44.             @Override    
  45.             public Thread newThread(Runnable r) {    
  46.                 return new Thread(r, "ThreadPool #" + mCount.getAndIncrement());    
  47.             }    
  48.         };    
  49.           
  50. }  



最后别忘了加入权限

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

在编程中遇到的问题:
Exception:  Unable to start Service Discovery 
java.io.IOException: Unable to start Service Discovery错误

1,必须保证客户端,服务器端中的UUID统一,客户端格式为:UUID格式一般是"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

例如:UUID.fromString("81403000-13df-b000-7cf4-350b4a2110ee");

2,必须进行配对处理后方可能够连接



扩展:蓝牙后台配对实现(网上看到的整理如下)

[java]  view plain copy
  1. static public boolean createBond(Class btClass, BluetoothDevice btDevice)  
  2.             throws Exception {  
  3.         Method createBondMethod = btClass.getMethod("createBond");  
  4.         Log.i("life""createBondMethod = " + createBondMethod.getName());  
  5.         Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
  6.         return returnValue.booleanValue();  
  7.     }  
  8.   
  9.     static public boolean setPin(Class btClass, BluetoothDevice btDevice,  
  10.             String str) throws Exception {  
  11.         Boolean returnValue = null;  
  12.         try {  
  13.             Method removeBondMethod = btClass.getDeclaredMethod("setPin",  
  14.                     new Class[] { byte[].class });  
  15.             returnValue = (Boolean) removeBondMethod.invoke(btDevice,  
  16.                     new Object[] { str.getBytes() });  
  17.             Log.i("life""returnValue = " + returnValue);  
  18.         } catch (SecurityException e) {  
  19.             // throw new RuntimeException(e.getMessage());  
  20.             e.printStackTrace();  
  21.         } catch (IllegalArgumentException e) {  
  22.             // throw new RuntimeException(e.getMessage());  
  23.             e.printStackTrace();  
  24.         } catch (Exception e) {  
  25.             // TODO Auto-generated catch block  
  26.             e.printStackTrace();  
  27.         }  
  28.         return returnValue;  
  29.     }  
  30.   
  31.     // 取消用户输入  
  32.     static public boolean cancelPairingUserInput(Class btClass,  
  33.             BluetoothDevice device) throws Exception {  
  34.         Method createBondMethod = btClass.getMethod("cancelPairingUserInput");  
  35.         // cancelBondProcess()  
  36.         Boolean returnValue = (Boolean) createBondMethod.invoke(device);  
  37.         Log.i("life""cancelPairingUserInputreturnValue = " + returnValue);  
  38.         return returnValue.booleanValue();  
  39.     }  


然后监听蓝牙配对的广播  匹配“android.bluetooth.device.action.PAIRING_REQUEST”这个action
然后调用上面的setPin(mDevice.getClass(), mDevice, "1234"); // 手机和蓝牙采集器配对
createBond(mDevice.getClass(), mDevice);
cancelPairingUserInput(mDevice.getClass(), mDevice);
mDevice是你要去连接的那个蓝牙的对象 , 1234为配对的pin码

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值