Android藍牙通信的完整指南

Android設備可以通過藍牙和其他設備進行通信,包括其他Android設備和外部設備,如藍牙耳機、印表機和感測器等。在本指南中,我們將詳細介紹如何使用Android藍牙API建立和管理藍牙連接。

一、檢查設備是否支持藍牙

首先,我們需要檢查當前設備是否支持藍牙功能。

    private boolean isBluetoothSupported() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        return bluetoothAdapter != null;
    }

使用上述代碼可以檢查設備是否支持藍牙功能。如果返回true,則設備支持藍牙功能。

二、開啟藍牙

在使用藍牙功能之前,需要確保藍牙已經開啟。

    private boolean isBluetoothEnabled() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        return bluetoothAdapter != null && bluetoothAdapter.isEnabled();
    }

    private void enableBluetooth(Activity activity) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        activity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(this, "藍牙已打開", Toast.LENGTH_SHORT).show();
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(this, "無法打開藍牙", Toast.LENGTH_SHORT).show();
            }
        }
    }

使用上述代碼可以檢查藍牙是否已開啟。如果返回true,則藍牙已經開啟。如果返回false,則需要啟動啟用藍牙對話框以請求開啟藍牙。

三、搜索設備

在與其他設備進行通信之前,需要搜索周圍的設備。在搜索設備之前,需要確保藍牙已經開啟。

    private void startDiscovery() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        bluetoothAdapter.startDiscovery();
        Toast.makeText(this, "搜索設備中...", Toast.LENGTH_SHORT).show();
    }

    private final BroadcastReceiver discoveryReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.d(TAG, "發現設備:" + device.getName() + " - " + device.getAddress());
            }
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(discoveryReceiver, filter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(discoveryReceiver);
    }

使用上述代碼可以開始搜索設備。當找到設備時,會收到廣播,並且在日誌中列印設備名稱和地址。如果找不到設備,可以嘗試重新啟動搜索或檢查設備是否打開藍牙。

四、連接設備

當找到要連接的設備時,需要建立連接。建立連接前,需要確保藍牙已經開啟。

    private void connect(String address) {
        BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
        BluetoothSocket socket = null;
        try {
            socket = device.createRfcommSocketToServiceRecord(MY_UUID);
            socket.connect();
            Log.d(TAG, "連接成功:" + device.getName());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

使用上述代碼可以連接指定地址的設備。如果連接成功,則會在日誌中列印設備名稱。如果連接失敗,則會拋出IOException。

五、數據傳輸

連接建立後,可以開始在設備之間傳輸數據。以下代碼演示如何發送和接收文本數據。

    private void send(String message) {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            return;
        }

        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
        BluetoothSocket socket = null;
        OutputStream outputStream = null;
        try {
            socket = device.createRfcommSocketToServiceRecord(MY_UUID);
            socket.connect();
            outputStream = socket.getOutputStream();
            outputStream.write(message.getBytes());
            Log.d(TAG, "消息發送成功:" + message);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private final BroadcastReceiver receiveReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
                Log.d(TAG, "連接成功");
            } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                Log.d(TAG, "連接斷開");
            } else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
                Log.d(TAG, "斷開請求");
            } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            }
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiveReceiver, filter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(receiveReceiver);
    }

使用上述代碼可以在設備之間傳輸文本數據。發送消息時,使用OutputStream將文本字元串轉換為位元組,並通過BluetoothSocket發送。在接收消息時,使用BroadcastReceiver監聽連接的狀態,並根據狀態更新UI或執行其他操作。

六、總結

本指南中介紹了如何使用Android藍牙API建立和管理藍牙連接。需要注意的是,在使用藍牙功能之前,需要確保藍牙已經開啟,並且在連接設備之前,需要確保已經搜索到要連接的設備。為了傳輸數據,可以使用OutputStream將文本轉換為位元組並發送。在接收數據時,可以使用BroadcastReceiver監聽連接狀態並執行操作。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/186240.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-11-27 05:45
下一篇 2024-11-27 05:45

相關推薦

  • Java JsonPath 效率優化指南

    本篇文章將深入探討Java JsonPath的效率問題,並提供一些優化方案。 一、JsonPath 簡介 JsonPath是一個可用於從JSON數據中獲取信息的庫。它提供了一種DS…

    編程 2025-04-29
  • 運維Python和GO應用實踐指南

    本文將從多個角度詳細闡述運維Python和GO的實際應用,包括監控、管理、自動化、部署、持續集成等方面。 一、監控 運維中的監控是保證系統穩定性的重要手段。Python和GO都有強…

    編程 2025-04-29
  • Python應用程序的全面指南

    Python是一種功能強大而簡單易學的編程語言,適用於多種應用場景。本篇文章將從多個方面介紹Python如何應用於開發應用程序。 一、Web應用程序 目前,基於Python的Web…

    編程 2025-04-29
  • Python wordcloud入門指南

    如何在Python中使用wordcloud庫生成文字雲? 一、安裝和導入wordcloud庫 在使用wordcloud前,需要保證庫已經安裝並導入: !pip install wo…

    編程 2025-04-29
  • Python字元轉列表指南

    Python是一個極為流行的腳本語言,在數據處理、數據分析、人工智慧等領域廣泛應用。在很多場景下需要將字元串轉換為列表,以便於操作和處理,本篇文章將從多個方面對Python字元轉列…

    編程 2025-04-29
  • 打造照片漫畫生成器的完整指南

    本文將分享如何使用Python編寫一個簡單的照片漫畫生成器,本文所提到的所有代碼和技術都適用於初學者。 一、環境準備 在開始編寫代碼之前,我們需要準備一些必要的環境。 首先,需要安…

    編程 2025-04-29
  • 如何在Java中拼接OBJ格式的文件並生成完整的圖像

    OBJ格式是一種用於表示3D對象的標準格式,通常由一組頂點、面和紋理映射坐標組成。在本文中,我們將討論如何將多個OBJ文件拼接在一起,生成一個完整的3D模型。 一、讀取OBJ文件 …

    編程 2025-04-29
  • Python小波分解入門指南

    本文將介紹Python小波分解的概念、基本原理和實現方法,幫助初學者掌握相關技能。 一、小波變換概述 小波分解是一種廣泛應用於數字信號處理和圖像處理的方法,可以將信號分解成多個具有…

    編程 2025-04-29
  • Python初學者指南:第一個Python程序安裝步驟

    在本篇指南中,我們將通過以下方式來詳細講解第一個Python程序安裝步驟: Python的安裝和環境配置 在命令行中編寫和運行第一個Python程序 使用IDE編寫和運行第一個Py…

    編程 2025-04-29
  • Python起筆落筆全能開發指南

    Python起筆落筆是指在編寫Python代碼時的編寫習慣。一個好的起筆落筆習慣可以提高代碼的可讀性、可維護性和可擴展性,本文將從多個方面進行詳細闡述。 一、變數命名 變數命名是起…

    編程 2025-04-29

發表回復

登錄後才能評論