Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> Android 藍牙操作詳解,android藍牙詳解

Android 藍牙操作詳解,android藍牙詳解

編輯:關於android開發

Android 藍牙操作詳解,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);      }

 

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();
          }
     }
}  

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();               }           }      }

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved