欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android 藍牙開發(fā)實例解析

 更新時間:2016年08月11日 11:44:38   投稿:lqh  
本文主要介紹Android 藍牙開發(fā),這里提供實例代碼和詳細解析實現(xiàn)方法,對開發(fā)Android藍牙開發(fā)的朋友提供簡單示例,有需要的朋友可以參考下

在使用手機時,藍牙通信給我們帶來很多方便。那么在Android手機中怎樣進行藍牙開發(fā)呢?本文以實例的方式講解Android藍牙開發(fā)的知識。

       1、使用藍牙的響應權限

XML/HTML代碼

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

        2、配置本機藍牙模塊

       在這里首先要了解對藍牙操作一個核心類BluetoothAdapter。

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();  
  
//直接打開系統(tǒng)的藍牙設置面板  
  
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  
  
startActivityForResult(intent, 0x1);  
  
//直接打開藍牙  
  
adapter.enable();  
  
//關閉藍牙  
  
adapter.disable();  
  
//打開本機的藍牙發(fā)現(xiàn)功能(默認打開120秒,可以將時間最多延長至300秒)  
  
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);  
  
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//設置持續(xù)時間(最多300秒) 

         3、搜索藍牙設備

       使用BluetoothAdapter的startDiscovery()方法來搜索藍牙設備。

       startDiscovery()方法是一個異步方法,調(diào)用后會立即返回。該方法會進行對其他藍牙設備的搜索,該過程會持續(xù)12秒。該方法調(diào)用后,搜索過程實際上是在一個System Service中進行的,所以可以調(diào)用cancelDiscovery()方法來停止搜索(該方法可以在未執(zhí)行discovery請求時調(diào)用)。

       請求Discovery后,系統(tǒng)開始搜索藍牙設備,在這個過程中,系統(tǒng)會發(fā)送以下三個廣播:

       ACTION_DISCOVERY_START:開始搜索

       ACTION_DISCOVERY_FINISHED:搜索結(jié)束

       ACTION_FOUND:找到設備,這個Intent中包含兩個extra fields:EXTRA_DEVICE和EXTRA_CLASS,分別包含BluetooDevice和BluetoothClass。

       我們可以自己注冊相應的BroadcastReceiver來接收響應的廣播,以便實現(xiàn)某些功能。

// 創(chuàng)建一個接收ACTION_FOUND廣播的BroadcastReceiver  
  
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {  
  
 public void onReceive(Context context, Intent intent) {  
  
  String action = intent.getAction();  
  
  // 發(fā)現(xiàn)設備  
  
  if (BluetoothDevice.ACTION_FOUND.equals(action)) {  
  
   // 從Intent中獲取設備對象  
  
   BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
  
   // 將設備名稱和地址放入array adapter,以便在ListView中顯示  
  
   mArrayAdapter.add(device.getName() + "\n" + device.getAddress());  
  }  
 }  
};  
  
// 注冊BroadcastReceiver  
  
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);  
  
registerReceiver(mReceiver, filter); // 不要忘了之后解除綁定 

        4、藍牙Socket通信

       如果打算建議兩個藍牙設備之間的連接,則必須實現(xiàn)服務器端與客戶端的機制。當兩個設備在同一個RFCOMM channel下分別擁有一個連接的BluetoothSocket,這兩個設備才可以說是建立了連接。

       服務器設備與客戶端設備獲取BluetoothSocket的途徑是不同的。服務器設備是通過accepted一個incoming connection來獲取的,而客戶端設備則是通過打開一個到服務器的RFCOMM channel來獲取的。

       服務器端的實現(xiàn)

       通過調(diào)用BluetoothAdapter的listenUsingRfcommWithServiceRecord(String, UUID)方法來獲取BluetoothServerSocket(UUID用于客戶端與服務器端之間的配對)。

       調(diào)用BluetoothServerSocket的accept()方法監(jiān)聽連接請求,如果收到請求,則返回一個BluetoothSocket實例(此方法為block方法,應置于新線程中)。

       如果不想在accept其他的連接,則調(diào)用BluetoothServerSocket的close()方法釋放資源(調(diào)用該方法后,之前獲得的BluetoothSocket實例并沒有close。但由于RFCOMM一個時刻只允許在一條channel中有一個連接,則一般在accept一個連接后,便close掉BluetoothServerSocket)。

private class AcceptThread extends Thread {  
  
 private final BluetoothServerSocket mmServerSocket;  
  
 public AcceptThread() {  
  
  // Use a temporary object that is later assigned to mmServerSocket,  
  
  // because mmServerSocket is final  
  
  BluetoothServerSocket tmp = null;  
  
  try {  
  
   // MY_UUID is the app's UUID string, also used by the client code  
   tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);  
  } catch (IOException e) { }  
  mmServerSocket = tmp;  
 }  
  
 public void run() {  
  BluetoothSocket socket = null;  
  
  // Keep listening until exception occurs or a socket is returned  
  
  while (true) {  
   try {  
    socket = mmServerSocket.accept();  
   } catch (IOException e) {  
    break;  
   }  
  
   // If a connection was accepted  
   if (socket != null) {  
    // Do work to manage the connection (in a separate thread)  
    manageConnectedSocket(socket);  
    mmServerSocket.close();  
    break;  
   }  
  }  
 }   
  
 /** Will cancel the listening socket, and cause the thread to finish */  
 public void cancel() {  
  try {  
   mmServerSocket.close();  
  } catch (IOException e) { }  
 }  
} 

        客戶端的實現(xiàn)

       通過搜索得到服務器端的BluetoothService。

       調(diào)用BluetoothService的listenUsingRfcommWithServiceRecord(String, UUID)方法獲取BluetoothSocket(該UUID應該同于服務器端的UUID)。

       調(diào)用BluetoothSocket的connect()方法(該方法為block方法),如果UUID同服務器端的UUID匹配,并且連接被服務器端accept,則connect()方法返回。

       注意:在調(diào)用connect()方法之前,應當確定當前沒有搜索設備,否則連接會變得非常慢并且容易失敗。

private class ConnectThread extends Thread { 
 private final BluetoothSocket mmSocket;  
  
 private final BluetoothDevice mmDevice;  
  
  
  
 public ConnectThread(BluetoothDevice device) {  
  
  // Use a temporary object that is later assigned to mmSocket,  
  
  // because mmSocket is final  
  
  BluetoothSocket tmp = null;  
  
  mmDevice = device;  
  
  
  
  // Get a BluetoothSocket to connect with the given BluetoothDevice  
  
  try {  
  
   // MY_UUID is the app's UUID string, also used by the server code  
   tmp = device.createRfcommSocketToServiceRecord(MY_UUID);  
  } catch (IOException e) { }  
  mmSocket = tmp;  
 }  
  
  
  
 public void run() {  
  // Cancel discovery because it will slow down the connection  
  mBluetoothAdapter.cancelDiscovery();  
  try {  
   // Connect the device through the socket. This will block  
   // until it succeeds or throws an exception  
   mmSocket.connect();  
  } catch (IOException connectException) {  
  
   // Unable to connect; close the socket and get out  
   try {  
    mmSocket.close();  
   } catch (IOException closeException) { }  
    return;  
  }  
  
   // Do work to manage the connection (in a separate thread)  
  manageConnectedSocket(mmSocket);  
 }  
  
 /** Will cancel an in-progress connection, and close the socket */  
  public void cancel() {  
  try {  
   mmSocket.close();  
  
  } catch (IOException e) { }  
  }  
} 

       5、連接管理(數(shù)據(jù)通信)

       分別通過BluetoothSocket的getInputStream()和getOutputStream()方法獲取InputStream和OutputStream。

       使用read(bytes[])和write(bytes[])方法分別進行讀寫操作。

       注意:read(bytes[])方法會一直block,知道從流中讀取到信息,而write(bytes[])方法并不是經(jīng)常的block(比如在另一設備沒有及時read或者中間緩沖區(qū)已滿的情況下,write方法會block)。

private class ConnectedThread extends Thread {  
  
 private final BluetoothSocket mmSocket;  
  
 private final InputStream mmInStream;  
  
 private final OutputStream mmOutStream;  
  
  
  
 public ConnectedThread(BluetoothSocket socket) {  
  
  mmSocket = socket;  
  
  InputStream tmpIn = null;  
  
  OutputStream tmpOut = null;  
  
  
  
  // Get the input and output streams, using temp objects because  
  
  // member streams are final  
  
  try {  
  
   tmpIn = socket.getInputStream();  
  
   tmpOut = socket.getOutputStream();  
  
  } catch (IOException e) { }  
  
  
  
  mmInStream = tmpIn;  
  
  mmOutStream = tmpOut;  
  
 }  
  
  
  
 public void run() {  
  
  byte[] buffer = new byte[1024]; // buffer store for the stream  
  
  int bytes; // bytes returned from read()  
  
  
  
  // Keep listening to the InputStream until an exception occurs  
  
  while (true) {  
  
   try {  
  
    // Read from the InputStream  
  
    bytes = mmInStream.read(buffer);  
  
    // Send the obtained bytes to the UI Activity  
  
    mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)  
  
      .sendToTarget();  
  
   } catch (IOException e) {  
  
    break;  
  
   }  
  
  }  
  
 }  
  
  
  
 /* Call this from the main Activity to send data to the remote device */  
  
 public void write(byte[] bytes) {  
  
  try {  
  
   mmOutStream.write(bytes);  
  
  } catch (IOException e) { }  
  
 }  
  
  
  
 /* Call this from the main Activity to shutdown the connection */  
  
 public void cancel() {  
  
  try {  
  
   mmSocket.close();  
  
  } catch (IOException e) { }  
  
 }  
  
}  

 以上就Android 藍牙的開發(fā)簡單示例代碼,后續(xù)繼續(xù)整理相關資料,謝謝大家對本站的支持!

相關文章

  • Android System fastboot 介紹和使用教程

    Android System fastboot 介紹和使用教程

    Fastboot是Android快速升級的一種方法,Fastboot的協(xié)議fastboot_protocol.txt在源碼目錄./bootable/bootloader/legacy下可以找到,本文給大家介紹Android System fastboot 介紹和使用教程,感興趣的朋友一起看看吧
    2024-01-01
  • Kotlin中的5種單例模式示例詳解

    Kotlin中的5種單例模式示例詳解

    這篇文章主要給大家介紹了關于Kotlin中5種單例模式的相關資料,分別包括了餓漢式、懶漢式 、線程安全的懶漢式 、雙重校驗鎖式以及靜態(tài)內(nèi)部類式,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下
    2018-08-08
  • Kotlin泛型的使用介紹

    Kotlin泛型的使用介紹

    泛型,即?"參數(shù)化類型",將類型參數(shù)化,可以用在類,接口,方法上。與?Java?一樣,Kotlin?也提供泛型,為類型安全提供保證,消除類型強轉(zhuǎn)的煩惱
    2022-09-09
  • Android NDK開發(fā)(C語言基本數(shù)據(jù)類型)

    Android NDK開發(fā)(C語言基本數(shù)據(jù)類型)

    這篇文章主要介紹了Android NDK開發(fā)中,C語言基本數(shù)據(jù)類型,主要以C語言包含的數(shù)據(jù)類型及基本類型展開相關資料,需要的朋友可以參考一下
    2021-12-12
  • Android入門之使用SQLite內(nèi)嵌式數(shù)據(jù)庫詳解

    Android入門之使用SQLite內(nèi)嵌式數(shù)據(jù)庫詳解

    Android內(nèi)帶SQLite內(nèi)嵌式數(shù)據(jù)庫了。這對于我們存儲一些更復雜的結(jié)構(gòu)化數(shù)據(jù)帶來了極大的便利。本文就來和大家聊聊具體的使用方法,希望對大家有所幫助
    2022-12-12
  • 詳解android 通過uri獲取bitmap圖片并壓縮

    詳解android 通過uri獲取bitmap圖片并壓縮

    這篇文章主要介紹了詳解android 通過uri獲取bitmap圖片并壓縮的相關資料,希望通過本文能幫助到大家,讓大家理解這部分內(nèi)容,需要的朋友可以參考下
    2017-10-10
  • Android動畫之小球擬合動畫實例

    Android動畫之小球擬合動畫實例

    這篇文章主要介紹了Android動畫之小球擬合動畫實例的相關資料,需要的朋友可以參考下
    2017-07-07
  • Flutter如何輕松實現(xiàn)動態(tài)更新ListView淺析

    Flutter如何輕松實現(xiàn)動態(tài)更新ListView淺析

    在Android中通常都會用到listview.那么flutter里面怎么用呢?下面這篇文章主要給大家介紹了關于Flutter如何輕松實現(xiàn)動態(tài)更新ListView的相關資料,需要的朋友可以參考下
    2022-02-02
  • 實例詳解Android Webview攔截ajax請求

    實例詳解Android Webview攔截ajax請求

    本篇內(nèi)容主要給大家講解了Android Webview攔截ajax請求的詳細講解,需要的朋友一起來學習一下。
    2017-11-11
  • Android中@id和@+id及@android:id的區(qū)別介紹

    Android中@id和@+id及@android:id的區(qū)別介紹

    這篇文章主要給大家介紹了關于Android中@id和@+id及@android:id的區(qū)別的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-09-09

最新評論