設定藍牙
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
您必須先讓應用程式透過藍牙或藍牙低功耗技術進行通訊,
。
請確認已啟用。請注意,只有在
<uses-feature.../>
資訊清單檔案項目中的 android:required
屬性為
已設為 false
。
如果不支援藍牙,請妥善停用所有藍牙功能
接著介紹網際網路通訊層
包括兩項主要的安全防護功能如果支援藍牙但已停用,您可以要求
使用者不需離開您的應用程式即可啟用藍牙。
第一步是
新增藍牙權限
新增到資訊清單檔案,即可使用下列 API。
取得權限後,系統會透過兩個步驟完成藍牙設定
使用 BluetoothAdapter
:
取得 BluetoothAdapter
。
任何及所有藍牙活動都需要 BluetoothAdapter
。
BluetoothAdapter
代表裝置專屬的藍牙轉接器 (
藍牙無線電)。如要取得 BluetoothAdapter
,首先需要
Context
。請使用這個結構定義
BluetoothManager
的例項
系統服務正在撥打 BluetoothManager#getAdapter
即可獲得 BluetoothAdapter
物件如果 getAdapter()
傳回空值,
則裝置不支援藍牙
例如:
Kotlin
val bluetoothManager: BluetoothManager = getSystemService(BluetoothManager::class.java)
val bluetoothAdapter: BluetoothAdapter? = bluetoothManager.getAdapter()
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
}
Java
BluetoothManager bluetoothManager = getSystemService(BluetoothManager.class);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
}
啟用藍牙。
接下來,請務必確保藍牙已啟用。致電
isEnabled()
到
檢查藍牙目前是否已啟用。如果這個方法傳回 false,
就會停用藍牙如需要求啟用藍牙,請撥打
startActivityForResult()
、
傳入
ACTION_REQUEST_ENABLE
。
意圖動作這個通話會透過以下方式提出啟用藍牙的要求:
系統設定 (不會停止應用程式)。
例如:
Kotlin
if (bluetoothAdapter?.isEnabled == false) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
Java
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
系統會顯示對話方塊,要求使用者授予啟用藍牙權限,如下所示:
圖 1.如果使用者授予權限,藍牙就會開始啟用
處理完成後 (或失敗) 後,焦點就會回到應用程式
圖1. 啟用藍牙對話方塊。
傳遞至 REQUEST_ENABLE_BT
常數
startActivityForResult()
是本機定義的整數,必須大於或等於 0。系統
會將這些常數傳回給您
onActivityResult()
敬上
做為 requestCode
參數的實作。
如果啟用藍牙成功,您的活動就會收到
RESULT_OK
結果程式碼
onActivityResult()
回呼。如果因為發生錯誤而未啟用藍牙 (或
使用者回應「拒絕」),那麼結果代碼是
RESULT_CANCELED
。
或者,應用程式也可以監聽
ACTION_STATE_CHANGED
敬上
廣播意圖;只要藍牙狀態,系統就會廣播意圖
並輸入變更內容這則直播含有多餘欄位
EXTRA_STATE
和
EXTRA_PREVIOUS_STATE
,
分別包含新舊藍牙狀態可能的值包括
這些額外欄位
STATE_TURNING_ON
、
STATE_ON
,
STATE_TURNING_OFF
,
和 STATE_OFF
。
如果應用程式需要偵測執行階段,監聽此廣播訊息就能派上用場
對藍牙狀態所做的變更。
提示:啟用可偵測性會自動啟用
藍牙。如果您打算定期啟用裝置搜尋功能
執行藍牙活動時,您可以略過前述的步驟 2。
在裝置上啟用藍牙後,就能同時使用傳統藍牙和
藍牙低功耗。
如果是經典藍牙,你可以尋找藍牙裝置
和
連結藍牙裝置。
針對藍牙低功耗裝置,你可以尋找 BLE 裝置、連線至 GATT 伺服器,以及
轉移 BLE 資料。
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-07-27 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-07-27 (世界標準時間)。"],[],[],null,["# Set up Bluetooth\n\nBefore your app can communicate over Bluetooth or Bluetooth Low Energy,\nyou need to verify that Bluetooth is supported on the device, and if it is,\nensure that it is enabled. Note that this check is only necessary if the\n`android:required` attribute in the `\u003cuses-feature.../\u003e` manifest file entry is\nset to `false`.\n\nIf Bluetooth isn't supported, then you should gracefully disable any Bluetooth\nfeatures. If Bluetooth is supported, but disabled, then you can request that the\nuser enable Bluetooth without leaving your app.\n\nThe first step is\n[adding the Bluetooth permissions](/develop/connectivity/bluetooth/bt-permissions#declare)\nto your manifest file in order to use the following APIs.\n\nOnce the permissions are in place, Bluetooth setup is accomplished in two steps\nusing the [`BluetoothAdapter`](/reference/android/bluetooth/BluetoothAdapter):\n\n1. Get the `BluetoothAdapter`.\n\n The `BluetoothAdapter` is required for any and all Bluetooth activity. The\n `BluetoothAdapter` represents the device's own Bluetooth adapter (the\n Bluetooth radio). To get a `BluetoothAdapter`, you first need to have a\n [`Context`](/reference/android/content/Context). Use this context to obtain\n an instance of the [`BluetoothManager`](/reference/android/bluetooth/BluetoothManager)\n system service. Calling [`BluetoothManager#getAdapter`](/reference/android/bluetooth/BluetoothManager#getAdapter)\n will give you a `BluetoothAdapter` object. If `getAdapter()` returns null,\n then the device doesn't support Bluetooth.\n\n For example: \n\n ### Kotlin\n\n ```kotlin\n val bluetoothManager: BluetoothManager = getSystemService(BluetoothManager::class.java)\n val bluetoothAdapter: BluetoothAdapter? = bluetoothManager.getAdapter()\n if (bluetoothAdapter == null) {\n // Device doesn't support Bluetooth\n }\n ```\n\n ### Java\n\n ```java\n BluetoothManager bluetoothManager = getSystemService(BluetoothManager.class);\n BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();\n if (bluetoothAdapter == null) {\n // Device doesn't support Bluetooth\n }\n ```\n2. Enable Bluetooth.\n\n Next, you need to ensure that Bluetooth is enabled. Call\n [`isEnabled()`](/reference/android/bluetooth/BluetoothAdapter#isEnabled()) to\n check whether Bluetooth is currently enabled. If this method returns false,\n then Bluetooth is disabled. To request that Bluetooth be enabled, call\n [`startActivityForResult()`](/reference/android/app/Activity#startActivityForResult(android.content.Intent,%20int)),\n passing in an\n [`ACTION_REQUEST_ENABLE`](/reference/android/bluetooth/BluetoothAdapter#ACTION_REQUEST_ENABLE)\n intent action. This call issues a request to enable Bluetooth through the\n system settings (without stopping your app).\n\n For example: \n\n ### Kotlin\n\n ```kotlin\n if (bluetoothAdapter?.isEnabled == false) {\n val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)\n startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)\n }\n ```\n\n ### Java\n\n ```java\n if (!bluetoothAdapter.isEnabled()) {\n Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);\n startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);\n }\n ```\n\n \u003cbr /\u003e\n\nA dialog appears requesting user permission to enable Bluetooth, as shown in\nfigure 1. If the user grants permission, the system begins to enable Bluetooth,\nand focus returns to your app once the process completes (or fails).\n\n\u003cbr /\u003e\n\n\n**Figure 1.** The enabling Bluetooth dialog.\n\nThe `REQUEST_ENABLE_BT` constant passed to\n[`startActivityForResult()`](/reference/android/app/Activity#startActivityForResult(android.content.Intent,%20int))\nis a locally-defined integer that must be greater than or equal to 0. The system\npasses this constant back to you in your\n[`onActivityResult()`](/reference/android/app/Activity#onActivityResult(int,%20int,%20android.content.Intent))\nimplementation as the `requestCode` parameter.\n\nIf enabling Bluetooth succeeds, your activity receives the\n[`RESULT_OK`](/reference/android/app/Activity#RESULT_OK) result code in the\n`onActivityResult()` callback. If Bluetooth was not enabled due to an error (or\nthe user responded \"Deny\") then the result code is\n[`RESULT_CANCELED`](/reference/android/app/Activity#RESULT_CANCELED).\n\nOptionally, your app can also listen for the\n[`ACTION_STATE_CHANGED`](/reference/android/bluetooth/BluetoothAdapter#ACTION_STATE_CHANGED)\nbroadcast intent, which the system broadcasts whenever the Bluetooth state\nchanges. This broadcast contains the extra fields\n[`EXTRA_STATE`](/reference/android/bluetooth/BluetoothAdapter#EXTRA_STATE) and\n[`EXTRA_PREVIOUS_STATE`](/reference/android/bluetooth/BluetoothAdapter#EXTRA_PREVIOUS_STATE),\ncontaining the new and old Bluetooth states, respectively. Possible values for\nthese extra fields are\n[`STATE_TURNING_ON`](/reference/android/bluetooth/BluetoothAdapter#STATE_TURNING_ON),\n[`STATE_ON`](/reference/android/bluetooth/BluetoothAdapter#STATE_ON),\n[`STATE_TURNING_OFF`](/reference/android/bluetooth/BluetoothAdapter#STATE_TURNING_OFF),\nand [`STATE_OFF`](/reference/android/bluetooth/BluetoothAdapter#STATE_OFF).\nListening for this broadcast can be useful if your app needs to detect runtime\nchanges made to the Bluetooth state. \n**Tip:** Enabling discoverability automatically enables Bluetooth. If you plan to consistently enable device discoverability before performing Bluetooth activity, you can skip step 2 in the earlier steps.\n\nOnce Bluetooth is enabled on the device, you can use both Bluetooth classic and\nBluetooth Low Energy.\n\nFor Bluetooth classic, you can [find Bluetooth devices](/develop/connectivity/bluetooth/find-bluetooth-devices)\nand\n[connect to Bluetooth devices](/develop/connectivity/bluetooth/connect-bluetooth-devices).\n\nFor Bluetooth Low Energy, you can [find BLE devices](/develop/connectivity/bluetooth/find-ble-devices), [connect to a GATT server](/develop/connectivity/bluetooth/connect-gatt-server), and\n[transfer BLE data](/develop/connectivity/bluetooth/transfer-ble-data)."]]