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

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.