android藍牙開發 藍牙設備的查找和連接

Android對於藍牙開發從2.0版本的sdk才開始支持,而且模擬器不支持,測試至少需要兩部手機,所以制約瞭很多技術人員的開發。
      1.  首先,要操作藍牙,先要在AndroidManifest.xml裡加入權限

  // 管理藍牙設備的權限  

<uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN" />

 // 使用藍牙設備的權限  

<uses-permissionandroid:name="android.permission.BLUETOOTH" />

2.打開藍牙
獲得藍牙適配器(android.bluetooth.BluetoothAdapter),檢查該設備是否支持藍牙,如果支持,就打開藍牙。

[java]
// 檢查設備是否支持藍牙      
adapter = BluetoothAdapter.getDefaultAdapter();    
if (adapter == null)    
{    
    // 設備不支持藍牙      
}    
// 打開藍牙      
if (!adapter.isEnabled())    
{    
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);    
    // 設置藍牙可見性,最多300秒      
    intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);    
    context.startActivity(intent);    
}   

// 檢查設備是否支持藍牙   
adapter = BluetoothAdapter.getDefaultAdapter();  
if (adapter == null)  
{  
    // 設備不支持藍牙   
}  
// 打開藍牙   
if (!adapter.isEnabled())  
{  
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  
    // 設置藍牙可見性,最多300秒   
    intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);  
    context.startActivity(intent);  

3.獲取已配對的藍牙設備(android.bluetooth.BluetoothDevice)
首次連接某藍牙設備需要先配對,一旦配對成功,該設備的信息會被保存,以後連接時無需再配對,所以已配對的設備不一定是能連接的。

[java]
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();    
Set<BluetoothDevice> devices = adapter.getBondedDevices();    
for(int i=0; i<devices.size(); i++)    
{    
    BluetoothDevice device = (BluetoothDevice) devices.iterator().next();    
   System.out.println(device.getName());    
}   

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();  
Set<BluetoothDevice> devices = adapter.getBondedDevices();  
for(int i=0; i<devices.size(); i++)  
{  
    BluetoothDevice device = (BluetoothDevice) devices.iterator().next();  
   System.out.println(device.getName());  

4.搜索周圍的藍牙設備
適配器搜索藍牙設備後將結果以廣播形式傳出去,所以需要自定義一個繼承廣播的類,在onReceive方法中獲得並處理藍牙設備的搜索結果。

[java]
// 設置廣播信息過濾      
IntentFilter intentFilter = new IntentFilter();    
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);    
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);    
intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);    
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);    
// 註冊廣播接收器,接收並處理搜索結果      
context.registerReceiver(receiver, intentFilter);    
// 尋找藍牙設備,android會將查找到的設備以廣播形式發出去      
adapter.startDiscovery();   

// 設置廣播信息過濾   
IntentFilter intentFilter = new IntentFilter();  
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);  
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);  
intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);  
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);  
// 註冊廣播接收器,接收並處理搜索結果   
context.registerReceiver(receiver, intentFilter);  
// 尋找藍牙設備,android會將查找到的設備以廣播形式發出去   
adapter.startDiscovery();  自定義廣播類

[java]
private BroadcastReceiver receiver = 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);    
            System.out.println(device.getName());    
       }    
   }    

private BroadcastReceiver receiver = 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);  
            System.out.println(device.getName());  
       }  
   }  
}
5.藍牙設備的配對和狀態監視

[java]
private BroadcastReceiver receiver = 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);    
            System.out.println(device.getName());    
            // 如果查找到的設備符合要連接的設備,處理      
            if (device.getName().equalsIgnoreCase(name)) {    
                // 搜索藍牙設備的過程占用資源比較多,一旦找到需要連接的設備後需要及時關閉搜索      
                adapter.cancelDiscovery();    
                // 獲取藍牙設備的連接狀態      
                connectState = device.getBondState();    
                switch (connectState) {    
                    // 未配對      
                    case BluetoothDevice.BOND_NONE:    
                        // 配對      
                        try {    
                            Method createBondMethod = BluetoothDevice.class.getMethod("createBond");    
                            createBondMethod.invoke(device);    
                        } catch (Exception e) {     
                            e.printStackTrace();    
                        }    
                        break;    
                    // 已配對      
                    case BluetoothDevice.BOND_BONDED:    
                        try {    
                            // 連接      
                           connect(device);    
                        } catch (IOException e) {    
                            e.printStackTrace();    
                        }    
                        break;    
                }    
            }    
       } else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {    
            // 狀態改變的廣播      
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);    
            if (device.getName().equalsIgnoreCase(name)) {     
                connectState = device.getBondState();    
                switch (connectState) {    
                    case BluetoothDevice.BOND_NONE:    
                        break;    
                    case BluetoothDevice.BOND_BONDING:    
                        break;    
                    case BluetoothDevice.BOND_BONDED:    
                        try {    
                            // 連接      
                            connect(device);    
                        } catch (IOException e) {    
                            e.printStackTrace();    
                        }    
                        break;    
                }    
            }    
        }    
    }    
}   

private BroadcastReceiver receiver = 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);  
            System.out.println(device.getName());  
            // 如果查找到的設備符合要連接的設備,處理   
            if (device.getName().equalsIgnoreCase(name)) {  
                // 搜索藍牙設備的過程占用資源比較多,一旦找到需要連接的設備後需要及時關閉搜索   
                adapter.cancelDiscovery();  
                // 獲取藍牙設備的連接狀態   
                connectState = device.getBondState();  
                switch (connectState) {  
                    // 未配對   
                    case BluetoothDevice.BOND_NONE:  
                        // 配對   
                        try {  
                            Method createBondMethod = BluetoothDevice.class.getMethod("createBond");  
                            createBondMethod.invoke(device);  
                        } catch (Exception e) {   
                            e.printStackTrace();  
                        }  
                        break;  
                    // 已配對   
                    case BluetoothDevice.BOND_BONDED:  
                        try {  
                            // 連接   
                           connect(device);  
                        } catch (IOException e) {  
                            e.printStackTrace();  
                        }  
                        break;  
                }  
            }  
       } else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {  
            // 狀態改變的廣播   
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
            if (device.getName().equalsIgnoreCase(name)) {   
                connectState = device.getBondState();  
                switch (connectState) {  
                    case BluetoothDevice.BOND_NONE:  
                        break;  
                    case BluetoothDevice.BOND_BONDING:  
                        break;  
                    case BluetoothDevice.BOND_BONDED:  
                        try {  
                            // 連接   
                            connect(device);  
                        } catch (IOException e) {  
                            e.printStackTrace();  
                        }  
                        break;  
                }  
            }  
        }  
    }  
}  6.藍牙設備的連接

[java]
private void connect(BluetoothDevice device) throws IOException {    
    // 固定的UUID      
    final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";    
    UUID uuid = UUID.fromString(SPP_UUID);    
    BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);    
    socket.connect();    
}   

private void connect(BluetoothDevice device) throws IOException {  
    // 固定的UUID   
    final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";  
    UUID uuid = UUID.fromString(SPP_UUID);  
    BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);  
    socket.connect();  

本篇文章來源於 Linux公社網站(www.linuxidc.com)  原文鏈接:http://www.linuxidc.com/Linux/2011-12/48374.htm

 

1.BluetoothAdapter 顧名思義,藍牙適配器,直到我們建立bluetoothSocket連接之前,都要不斷操作它

      BluetoothAdapter裡的方法很多,常用的有以下幾個:

      cancelDiscovery() 根據字面意思,是取消發現,也就是說當我們正在搜索設備的時候調用這個方法將不再繼續搜索

      disable()關閉藍牙

      enable()打開藍牙,這個方法打開藍牙不會彈出提示,更多的時候我們需要問下用戶是否打開,一下這兩行代碼同樣是打開藍牙,不過會提示用戶:

Intemtenabler=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enabler,reCode);//同startActivity(enabler);

      getAddress()獲取本地藍牙地址

      getDefaultAdapter()獲取默認BluetoothAdapter,實際上,也隻有這一種方法獲取BluetoothAdapter

      getName()獲取本地藍牙名稱

      getRemoteDevice(String address)根據藍牙地址獲取遠程藍牙設備

      getState()獲取本地藍牙適配器當前狀態(感覺可能調試的時候更需要)

      isDiscovering()判斷當前是否正在查找設備,是返回true

      isEnabled()判斷藍牙是否打開,已打開返回true,否則,返回false

     listenUsingRfcommWithServiceRecord(String name,UUID uuid)根據名稱,UUID創建並返回BluetoothServerSocket,這是創建BluetoothSocket服務器端的第一步

      startDiscovery()開始搜索,這是搜索的第一步

    2.BluetoothDevice看名字就知道,這個類描述瞭一個藍牙設備

       createRfcommSocketToServiceRecord(UUIDuuid)根據UUID創建並返回一個BluetoothSocket

       這個方法也是我們獲取BluetoothDevice的目的——創建BluetoothSocket

       這個類其他的方法,如getAddress(),getName(),同BluetoothAdapter

    3.BluetoothServerSocket如果去除瞭Bluetooth相信大傢一定再熟悉不過瞭,既然是Socket,方法就應該都差不多,

這個類一種隻有三個方法

兩個重載的accept(),accept(inttimeout)兩者的區別在於後面的方法指定瞭過時時間,需要註意的是,執行這兩個方法的時候,直到接收到瞭客戶端的請求(或是過期之後),都會阻塞線程,應該放在新線程裡運行!

還有一點需要註意的是,這兩個方法都返回一個BluetoothSocket,最後的連接也是服務器端與客戶端的兩個BluetoothSocket的連接

      close()這個就不用說瞭吧,翻譯一下——關閉!

    4.BluetoothSocket,跟BluetoothServerSocket相對,是客戶端

一共5個方法,不出意外,都會用到

      close(),關閉

      connect()連接

      getInptuStream()獲取輸入流

      getOutputStream()獲取輸出流

      getRemoteDevice()獲取遠程設備,這裡指的是獲取bluetoothSocket指定連接的那個遠程藍牙設備

 

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。