码迷,mamicode.com
首页 > 移动开发 > 详细

Android学习之蓝牙操作

时间:2014-11-12 16:16:21      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   http   io   ar   os   java   sp   

Android 

蓝牙是一种支持设备短距离传输数据的无线技术。android在2.0以后提供了这方面的支持。 从查找蓝牙设备到能够相互通信要经过几个基本步骤(本机做为服务器): 1.设置权限 在manifest中配置
Xml代码 bubuko.com,布布扣 bubuko.com,布布扣
  1. <uses-permission android:name="android.permission.BLUETOOTH"/>  
  2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>  
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
2.启动蓝牙 首先要查看本机是否支持蓝牙,获取BluetoothAdapter蓝牙适配器对象
Java代码 bubuko.com,布布扣 bubuko.com,布布扣
  1. BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();  
  2. if(mBluetoothAdapter == null){  
  3.         //表明此手机不支持蓝牙  
  4.         return;  
  5. }  
  6. if(!mBluetoothAdapter.isEnabled()){ //蓝牙未开启,则开启蓝牙  
  7.             Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  
  8.             startActivityForResult(enableIntent, REQUEST_ENABLE_BT);  
  9. }  
  10. //......  
  11. public void onActivityResult(int requestCode, int resultCode, Intent data){  
  12.        if(requestCode == REQUEST_ENABLE_BT){  
  13.               if(requestCode == RESULT_OK){  
  14.                    //蓝牙已经开启   
  15.               }  
  16.        }  
  17. }  
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null){
        //表明此手机不支持蓝牙
        return;
}
if(!mBluetoothAdapter.isEnabled()){	//蓝牙未开启,则开启蓝牙
			Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
//......
public void onActivityResult(int requestCode, int resultCode, Intent data){
       if(requestCode == REQUEST_ENABLE_BT){
              if(requestCode == RESULT_OK){
                   //蓝牙已经开启 
              }
       }
}
3。发现蓝牙设备 这里可以细分为几个方面 (1)使本机蓝牙处于可见(即处于易被搜索到状态),便于其他设备发现本机蓝牙
Java代码 bubuko.com,布布扣 bubuko.com,布布扣
  1. //使本机蓝牙在300秒内可被搜索  
  2. private void ensureDiscoverable() {  
  3.         if (mBluetoothAdapter.getScanMode() !=  
  4.             BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {  
  5.             Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);  
  6.             discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);  
  7.             startActivity(discoverableIntent);  
  8.         }  
  9. }  
//使本机蓝牙在300秒内可被搜索
private void ensureDiscoverable() {
        if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
}
(2)查找已经配对的蓝牙设备,即以前已经配对过的设备
Java代码 bubuko.com,布布扣 bubuko.com,布布扣
  1. Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();  
  2. if (pairedDevices.size() > 0) {  
  3.     findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);  
  4.     for (BluetoothDevice device : pairedDevices) {  
  5.         //device.getName() +" "+ device.getAddress());  
  6.     }  
  7. else {  
  8.     mPairedDevicesArrayAdapter.add("没有找到已匹对的设备");  
  9. }  
		Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
		if (pairedDevices.size() > 0) {
			findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
			for (BluetoothDevice device : pairedDevices) {
				//device.getName() +" "+ device.getAddress());
			}
		} else {
			mPairedDevicesArrayAdapter.add("没有找到已匹对的设备");
		}
(3)通过mBluetoothAdapter.startDiscovery();搜索设备,要获得此搜索的结果需要注册 一个BroadcastReceiver来获取。先注册再获取信息,然后处理
Java代码 bubuko.com,布布扣 bubuko.com,布布扣
  1. //注册,当一个设备被发现时调用onReceive  
  2. IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);  
  3.         this.registerReceiver(mReceiver, filter);  
  4.   
  5. //当搜索结束后调用onReceive  
  6. filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);  
  7.         this.registerReceiver(mReceiver, filter);  
  8. //.......  
  9. private BroadcastReceiver mReceiver = new BroadcastReceiver() {  
  10.         @Override  
  11.         public void onReceive(Context context, Intent intent) {  
  12.             String action = intent.getAction();  
  13.             if(BluetoothDevice.ACTION_FOUND.equals(action)){  
  14.                  BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
  15.                   // 已经配对的则跳过  
  16.                  if (device.getBondState() != BluetoothDevice.BOND_BONDED) {  
  17.                       mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());  //保存设备地址与名字  
  18.                  }  
  19.             }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {  //搜索结束  
  20.                 if (mNewDevicesArrayAdapter.getCount() == 0) {  
  21.                     mNewDevicesArrayAdapter.add("没有搜索到设备");  
  22.                 }  
  23.             }  
  24.   
  25.         }  
  26. };  
//注册,当一个设备被发现时调用onReceive
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		this.registerReceiver(mReceiver, filter);

//当搜索结束后调用onReceive
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		this.registerReceiver(mReceiver, filter);
//.......
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(BluetoothDevice.ACTION_FOUND.equals(action)){
				 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
	              // 已经配对的则跳过
	             if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
	                  mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());  //保存设备地址与名字
	             }
			}else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {  //搜索结束
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                    mNewDevicesArrayAdapter.add("没有搜索到设备");
                }
			}

		}
};
4.建立连接 查找到设备 后,则需要建立本机与其他设备之间的连接。 一般用本机搜索其他蓝牙设备时,本机可以作为一个服务端,接收其他设备的连接。 启动一个服务器端的线程,死循环等待客户端的连接,这与ServerSocket极为相似。 这个线程在准备连接之前启动
Java代码 bubuko.com,布布扣 bubuko.com,布布扣
  1. //UUID可以看做一个端口号  
  2. private static final UUID MY_UUID =  
  3.         UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");  
  4.    //像一个服务器一样时刻监听是否有连接建立  
  5.     private class AcceptThread extends Thread{  
  6.         private BluetoothServerSocket serverSocket;  
  7.           
  8.         public AcceptThread(boolean secure){  
  9.             BluetoothServerSocket temp = null;  
  10.             try {  
  11.                 temp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(  
  12.                             NAME_INSECURE, MY_UUID);  
  13.             } catch (IOException e) {  
  14.                   Log.e("app", "listen() failed", e);  
  15.             }  
  16.             serverSocket = temp;  
  17.         }  
  18.           
  19.         public void run(){  
  20.             BluetoothSocket socket=null;  
  21.             while(true){  
  22.                 try {  
  23.                     socket = serverSocket.accept();  
  24.                 } catch (IOException e) {  
  25.                      Log.e("app", "accept() failed", e);  
  26.                      break;  
  27.                 }  
  28.             }  
  29.             if(socket!=null){  
  30.                 //此时可以新建一个数据交换线程,把此socket传进去  
  31.             }  
  32.         }  
  33.           
  34.         //取消监听  
  35.         public void cancel(){     
  36.             try {  
  37.                 serverSocket.close();  
  38.             } catch (IOException e) {  
  39.                 Log.e("app", "Socket Type" + socketType + "close() of server failed", e);  
  40.             }  
  41.         }  
  42.   
  43. }  
//UUID可以看做一个端口号
private static final UUID MY_UUID =
        UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
   //像一个服务器一样时刻监听是否有连接建立
    private class AcceptThread extends Thread{
    	private BluetoothServerSocket serverSocket;
    	
    	public AcceptThread(boolean secure){
    		BluetoothServerSocket temp = null;
    		try {
	    		temp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(
	    					NAME_INSECURE, MY_UUID);
    		} catch (IOException e) {
				  Log.e("app", "listen() failed", e);
			}
    		serverSocket = temp;
    	}
    	
    	public void run(){
    		BluetoothSocket socket=null;
    		while(true){
    			try {
					socket = serverSocket.accept();
				} catch (IOException e) {
					 Log.e("app", "accept() failed", e);
	                 break;
				}
    		}
    		if(socket!=null){
    			//此时可以新建一个数据交换线程,把此socket传进去
    		}
    	}
    	
    	//取消监听
    	public void cancel(){	
	        try {
	            serverSocket.close();
	        } catch (IOException e) {
	            Log.e("app", "Socket Type" + socketType + "close() of server failed", e);
	        }
    	}

}
搜索到设备后可以获取设备的地址,通过此地址获取一个BluetoothDeviced对象,可以看做客户端,通过此对象device.createRfcommSocketToServiceRecord(MY_UUID);同一个UUID可与服务器建立连接获取另一个socket对象,由此服务端与客户端各有一个socket对象,此时 他们可以互相交换数据了。 创立客户端socket可建立线程
Java代码 bubuko.com,布布扣 bubuko.com,布布扣
  1.  //另一个设备去连接本机,相当于客户端  
  2.  private class ConnectThread extends Thread{  
  3.     private BluetoothSocket socket;  
  4.     private BluetoothDevice device;  
  5.     public ConnectThread(BluetoothDevice device,boolean secure){  
  6.         this.device = device;  
  7.         BluetoothSocket tmp = null;  
  8.         try {  
  9.     tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);  
  10. catch (IOException e) {  
  11.      Log.e("app", "create() failed", e);  
  12. }  
  13.     }  
  14.       
  15.     public void run(){  
  16.         mBluetoothAdapter.cancelDiscovery();    //取消设备查找  
  17.         try {  
  18.     socket.connect();  
  19. catch (IOException e) {  
  20.     try {  
  21.         socket.close();  
  22.     } catch (IOException e1) {  
  23.          Log.e("app", "unable to close() "+  
  24.                           " socket during connection failure", e1);  
  25.     }  
  26.     connetionFailed();  //连接失败  
  27.     return;  
  28. }  
  29.       //此时可以新建一个数据交换线程,把此socket传进去  
  30.     }  
  31.       
  32.       public void cancel() {  
  33.            try {  
  34.                socket.close();  
  35.            } catch (IOException e) {  
  36.                Log.e("app", "close() of connect  socket failed", e);  
  37.            }  
  38.        }  
  39.  }  
    //另一个设备去连接本机,相当于客户端
    private class ConnectThread extends Thread{
    	private BluetoothSocket socket;
    	private BluetoothDevice device;
    	public ConnectThread(BluetoothDevice device,boolean secure){
    		this.device = device;
    		BluetoothSocket tmp = null;
    		try {
				tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
			} catch (IOException e) {
				 Log.e("app", "create() failed", e);
			}
    	}
    	
    	public void run(){
    		mBluetoothAdapter.cancelDiscovery();	//取消设备查找
    		try {
				socket.connect();
			} catch (IOException e) {
				try {
					socket.close();
				} catch (IOException e1) {
					 Log.e("app", "unable to close() "+
	                            " socket during connection failure", e1);
				}
				connetionFailed();	//连接失败
				return;
			}
	        //此时可以新建一个数据交换线程,把此socket传进去
    	}
    	
    	  public void cancel() {
              try {
                  socket.close();
              } catch (IOException e) {
                  Log.e("app", "close() of connect  socket failed", e);
              }
          }
    }
5.建立数据通信线程,进行读取数据
Java代码 bubuko.com,布布扣 bubuko.com,布布扣
  1. //建立连接后,进行数据通信的线程  
  2.     private class ConnectedThread extends Thread{  
  3.         private BluetoothSocket socket;  
  4.         private InputStream inStream;  
  5.         private OutputStream outStream;  
  6.           
  7.         public ConnectedThread(BluetoothSocket socket){  
  8.               
  9.             this.socket = socket;  
  10.             try {  
  11.                 //获得输入输出流  
  12.                 inStream = socket.getInputStream();  
  13.                 outStream = socket.getOutputStream();  
  14.             } catch (IOException e) {  
  15.                 Log.e("app", "temp sockets not created", e);  
  16.             }  
  17.         }  
  18.           
  19.         public void run(){  
  20.             byte[] buff = new byte[1024];  
  21.             int len=0;  
  22.             //读数据需不断监听,写不需要  
  23.             while(true){  
  24.                 try {  
  25.                     len = inStream.read(buff);  
  26.                     //把读取到的数据发送给UI进行显示  
  27.                     Message msg = handler.obtainMessage(BluetoothChat.MESSAGE_READ,  
  28.                             len, -1, buff);  
  29.                     msg.sendToTarget();  
  30.                 } catch (IOException e) {  
  31.                     Log.e("app", "disconnected", e);  
  32.                     connectionLost();   //失去连接  
  33.                     start();    //重新启动服务器  
  34.                     break;  
  35.                 }  
  36.             }  
  37.         }  
  38.           
  39.           
  40.         public void write(byte[] buffer) {  
  41.             try {  
  42.                 outStream.write(buffer);  
  43.   
  44.                 // Share the sent message back to the UI Activity  
  45.                 handler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)  
  46.                         .sendToTarget();  
  47.             } catch (IOException e) {  
  48.                 Log.e("app", "Exception during write", e);  
  49.             }  
  50.         }  
  51.   
  52.         public void cancel() {  
  53.             try {  
  54.                 socket.close();  
  55.             } catch (IOException e) {  
  56.                 Log.e("app", "close() of connect socket failed", e);  
  57.             }  
  58.         }  
  59.     }  
//建立连接后,进行数据通信的线程
    private class ConnectedThread extends Thread{
    	private BluetoothSocket socket;
    	private InputStream inStream;
    	private OutputStream outStream;
    	
    	public ConnectedThread(BluetoothSocket socket){
    		
    		this.socket = socket;
    		try {
    			//获得输入输出流
				inStream = socket.getInputStream();
				outStream = socket.getOutputStream();
			} catch (IOException e) {
				Log.e("app", "temp sockets not created", e);
			}
    	}
    	
    	public void run(){
    		byte[] buff = new byte[1024];
    		int len=0;
    		//读数据需不断监听,写不需要
    		while(true){
    			try {
					len = inStream.read(buff);
					//把读取到的数据发送给UI进行显示
					Message msg = handler.obtainMessage(BluetoothChat.MESSAGE_READ,
							len, -1, buff);
					msg.sendToTarget();
				} catch (IOException e) {
					Log.e("app", "disconnected", e);
                    connectionLost();	//失去连接
                    start();	//重新启动服务器
                    break;
				}
    		}
    	}
    	
    	
    	public void write(byte[] buffer) {
            try {
                outStream.write(buffer);

                // Share the sent message back to the UI Activity
                handler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                Log.e("app", "Exception during write", e);
            }
        }

        public void cancel() {
            try {
                socket.close();
            } catch (IOException e) {
                Log.e("app", "close() of connect socket failed", e);
            }
        }
    }
到这里,蓝牙通信的基本操作已经全部完成。

Android学习之蓝牙操作

标签:android   style   blog   http   io   ar   os   java   sp   

原文地址:http://www.cnblogs.com/summers/p/4092504.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!