lovebetAndroid 蓝牙操作详解。Android蓝牙操作笔记。

1.启用蓝牙并而装备处可窥见状态    

   1.1
在应用BluetoothAdapter类的实例进操作前,应启用isEnable()方法检查设备是否启用了蓝牙适配器。

 

    // 使用意图提示用户启用蓝牙,并设装备处可窥见状态

     private void startBluetooth()
{

          BluetoothAdapter
bt = BluetoothAdapter.getDefaultAdapter();

           //
检测蓝牙是否开启

           if (!bt.isEnabled())
{

              Intent
enableIntent = new Intent(

                        BluetoothAdapter. ACTION_REQUEST_ENABLE);

              startActivityForResult(enableIntent, REQUEST_ENABLE_BT);

          }

     }

 1.2返回意图活动经常,调用onActivityResult(),可以领取主设备名称与mac地址

 

 protected void onActivityResult(int requestCode, int resultCode, Intent
data) {

           if (requestCode
== REQUEST_ENABLE_BT

                   &&
resultCode == Activity. RESULT_OK) {

              BluetoothAdapter
bt = BluetoothAdapter.getDefaultAdapter();

              String
address = bt.getAddress();

              String
name = bt.getName();

              String
toastText = name + ”
:” +
address;

              Toast. makeText(this, toastText,
Toast.LENGTH_LONG).show();

              discoverable();

          }

     }

1.3
请求用户授权,让设备可让其他临近设备发现:

     //
请求用户授权,让设备在120秒内处于可窥见状态

     private void discoverable() {

          Intent
discoverableIntent = new Intent(

                    BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

          startActivity(discoverableIntent);

     }

蓝牙凡是同等种植支持设备短距离传输数据的无线技术。android在2.0下供了当下点的支撑。 
打寻觅蓝牙设备及能相互通信要通过几独核心步骤(本机做啊服务器): 
1.设置权限 
在manifest中配置 

 

Xml代码  lovebet 1

2.一连启用蓝牙设备

 

 2.1于任何蓝牙应用,都必须于AndroidManifst.xml中上加如下权限:

     <uses-permission android:name= “android.permission.BLUETOOTH_ADMIN” />

     <uses-permission android:name= “android.permission.BLUETOOTH” />

 

 2.2 创建及其它蓝牙设备的套接字连接

   
 我们应该在一个线程内不停监听套接字流中之数。可以当该线程外写副连接的流淌。这种连是一个堵塞调用,由于蓝牙设备发现凡是一个放缓的过程,可能回落连接速率。所以,在一连其他设备之前若取消设备发现。

   
 蓝牙套接字连接时死调用,只以连年成还是连续装置发生很时才会回。BluetoothConnection一经实例化,就会创造及任何装备的总是,并初步监听来自连接装置的数量。

package com.example.blueoothdemo;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

/**
* 读写蓝牙设备
*
* @author hbbliyong
*
*/
public class BluetoothConnecion extends Thread {
     private final BluetoothSocket mSocket;
     private final InputStream mInStream;
     private final OutputStream mOutStream;
     byte[] buffer;
     private final BluetoothAdapter mAdapter;
     // 用于本应用程序唯一的UUID,
     private static final UUID MY_UUID = UUID
               .fromString(“fa87c0d0-afac-11de-8a39-0800200c9a66”);

     public BluetoothConnecion(BluetoothDevice device) {
          BluetoothSocket tmp = null;
          mAdapter = BluetoothAdapter.getDefaultAdapter();
          // 获得用于指定蓝牙连接的BluetoothSocket
          try {
               tmp =
device.createRfcommSocketToServiceRecord(MY_UUID);
          } catch (Exception e) {
               e.printStackTrace();
          }
          mSocket = tmp;

          // 在初线程中树立拟接字连接,避免FC
          Thread connectionThread = new Thread(new Runnable() {
               @Override
               public void run() {
                    // TODO Auto-generated method stub
                    // 始终取消发现,因为它会减低连接的速度
                    mAdapter.cancelDiscovery();

                    // 建立到BluetoothSocket的连接
                    try {
                         //
这是一个围堵调用,只在成功总是要坏时回来
                         mSocket.connect();
                    } catch (Exception e) {
                         e.printStackTrace();
                         // 设备连失败,关闭套接字
                         try {
                              mSocket.close();
                         } catch (Exception e2) {
                              // TODO: handle exception
                              e2.printStackTrace();
                         }
                    }
               }
          });

          connectionThread.start();

          InputStream tmpIn = null;
          OutputStream tmpOut = null;

          // 获得BluetoothSoket输入输出流
          try {
               tmpIn = mSocket.getInputStream();
               tmpOut = mSocket.getOutputStream();
               buffer = new byte[1024];
          } catch (Exception e) {
               e.printStackTrace();
          }
          mInStream = tmpIn;
          mOutStream = tmpOut;
     }

     public void run() {
          // 连接时保持监听InputStream
          while (true) {
               try {
                    // 从法接字流读取数据
                    mInStream.read(buffer);
                    // 向UI Activity发送获取的多寡
               } catch (Exception e) {
                    // TODO: handle exception
                    // 这里的良标志在连连的遗失
                    // 向UI Activity发送获取的数码
                    break;
               }
          }
     }
    
     public void write(byte[] buffer)
     {
          try {
               mOutStream.write(buffer);
          } catch (Exception e) {
               e.printStackTrace();
          }
     }
    
     public void cancel()
     {
          try {
               mSocket.close();
          } catch (Exception e) {
               // TODO: handle exception
               e.printStackTrace();
          }
     }
}

 

  1. <uses-permission android:name=”android.permission.BLUETOOTH”/>  
  2. <uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”/>  

3.监听与收受蓝牙连接要

 

   
 
当简单个蓝牙设备交互之前,其中一个通信设备必须由服务器的图。它赢得一个BluetoothServerSocket实例并监听入站请求。这个实例通过调用蓝牙适配器上之listenUsingRfcommWithServiceRecord()方法取得。有了此实例我们好透过start()方法开始监听来自远程设备的入站请求。

 

  //使主设备处可窥见状态

  Intent
disCoverableIntent = new Intent(

                 
    BluetoothAdapter. ACTION_REQUEST_DISCOVERABLE);

 
startActivityForResult(disCoverableIntent,DISCOVERY_REQUEST_BLUETOOTH );

 

 

//创建一个蓝牙服务器并收受连接

protected void onActivityResult(int requestCode, int resultCode, Intent
data) {

 

           if (requestCode
== DISCOVERY_REQUEST_BLUETOOTH ) {

               boolean isDiscoverable =
resultCode > 0;

               if (isDiscoverable)
{

                    //
UUID

                    // uuid=UUID.fromString(“a60f35f0-b93a-11de-8a39-08002009c666”);

                    final UUID uuid =
UUID.randomUUID();

                    final String serverName
= “BTServer” ;

                    final BluetoothAdapter bt =
BluetoothAdapter.getDefaultAdapter();

 

                    final BluetoothServerSocket
bluetoothServer;

 

                   Thread
listenThread = new Thread(new Runnable() {

 

                         @Override

                         public void run() {

                              // TODO Auto-generated
method stub

                              try {

                                  bluetoothServer
= bt.listenUsingRfcommWithServiceRecord(serverName, uuid);

                    BluetoothSocket
serverSocket = bluetoothServer.accept();

                    myHandleConnectionWiht(serverSocket);

 

                             } catch (Exception e) {

                                  e.printStackTrace();

                                  

                             }

                        }

 

                         private void myHandleConnectionWiht(

                                  BluetoothSocket
serverSocket) {

                              // TODO Auto-generated
method stub

                             

                        }

 

                   });

                   listenThread.start();

              }

          }

     }


2.起先蓝牙 
第一使翻看本机是否支持蓝牙,获取BluetoothAdapter蓝牙适配器对象 

Java代码  lovebet 2

  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. }  

3。发现蓝牙设备 
这里可以细分为几个点 
(1)使本机蓝牙处于可见(即地处容易为搜到状态),便于其他设施发现本机蓝牙 

Java代码  lovebet 3

  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. }  

(2)查找已经配对的蓝牙设备,即先都放流对过的装置 

Java代码  lovebet 4

  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. }  

(3)通过mBluetoothAdapter.startDiscovery();搜索设备,要抱这个搜索的结果需注册 
一个BroadcastReceiver来获取。先报还获取信息,然后处理 

Java代码  lovebet 5

  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. };  

4.成立连接 
追寻到装备 后,则用建立本机与任何设备中的连接。 
一般用本机搜索其他蓝牙设备时,本机可以当一个服务端,接收其他设备的连天。 
起步一个劳动器端的线程,死循环等待客户端的总是,这跟ServerSocket极为一般。 
此线程在准备连接之前启动 

Java代码  lovebet 6

  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. }  

觅到设备后方可抱装备的地址,通过这地点获取一个BluetoothDeviced对象,可以看做客户端,通过此目标device.createRfcommSocketToServiceRecord(MY_UUID);同一个UUID可及服务器建立连接获取其它一个socket对象,由此服务端与客户端各起一个socket对象,此时 
他俩得互相交换数据了。 
创办客户端socket可起线程 

Java代码  lovebet 7

  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.  }  

5.确立数量通信线程,进行读取数据 

Java代码  lovebet 8

  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.     }  

至这里,蓝牙通信的基本操作已经全部到位。