קל לארגן דפים בעזרת אוספים
אפשר לשמור ולסווג תוכן על סמך ההעדפות שלך.
כדי לאתר מכשירי BLE, צריך להשתמש
startScan()
. השיטה הזו
ScanCallback כפרמטר.
עליכם להטמיע את הקריאה החוזרת (callback) הזו, כי כך מוחזרות תוצאות הסריקה.
הסריקה שדורשת צריכת סוללה גבוהה, ולכן חשוב לשים לב לנקודות הבאות
הנחיות:
אחרי שמוצאים את המכשיר הרצוי, מפסיקים את הסריקה.
אף פעם לא לסרוק בלופ, ותמיד יש להגדיר מגבלת זמן לסריקה. מכשיר
היה זמין בעבר, ייתכן שיצא מהטווח וממשיך לסרוק
מרוקנת את הסוללה.
בדוגמה הבאה, אפליקציית BLE מספקת פעילות
(DeviceScanActivity) כדי לסרוק ולאתר מכשירים ומסכים זמינים של Bluetooth LE
אותם ברשימה למשתמש. קטע הקוד הבא מראה איך להפעיל ולהפסיק
לסרוק:
Kotlin
privatevalbluetoothLeScanner=bluetoothAdapter.bluetoothLeScannerprivatevarscanning=falseprivatevalhandler=Handler()// Stops scanning after 10 seconds.privatevalSCAN_PERIOD:Long=10000privatefunscanLeDevice(){if(!scanning){// Stops scanning after a pre-defined scan period.handler.postDelayed({scanning=falsebluetoothLeScanner.stopScan(leScanCallback)},SCAN_PERIOD)scanning=truebluetoothLeScanner.startScan(leScanCallback)}else{scanning=falsebluetoothLeScanner.stopScan(leScanCallback)}}
Java
privateBluetoothLeScannerbluetoothLeScanner=bluetoothAdapter.getBluetoothLeScanner();privatebooleanscanning;privateHandlerhandler=newHandler();// Stops scanning after 10 seconds.privatestaticfinallongSCAN_PERIOD=10000;privatevoidscanLeDevice(){if(!scanning){// Stops scanning after a predefined scan period.handler.postDelayed(newRunnable(){@Overridepublicvoidrun(){scanning=false;bluetoothLeScanner.stopScan(leScanCallback);}},SCAN_PERIOD);scanning=true;bluetoothLeScanner.startScan(leScanCallback);}else{scanning=false;bluetoothLeScanner.stopScan(leScanCallback);}}
דוגמת הקוד הבאה היא הטמעה של
ScanCallback
שהוא הממשק המשמש להצגת תוצאות של סריקת BLE. כשהתוצאות נמצאות,
הם נוספים למתאם רשימה ב-DeviceScanActivity כדי להציג
משתמש.
דוגמאות התוכן והקוד שבדף הזה כפופות לרישיונות המפורטים בקטע רישיון לתוכן. Java ו-OpenJDK הם סימנים מסחריים או סימנים מסחריים רשומים של חברת Oracle ו/או של השותפים העצמאיים שלה.
עדכון אחרון: 2025-07-27 (שעון UTC).
[[["התוכן קל להבנה","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 (שעון UTC)."],[],[],null,["# Find BLE devices\n\nTo find BLE devices, you use the\n[`startScan()`](/reference/android/bluetooth/le/BluetoothLeScanner#startScan(android.bluetooth.le.ScanCallback))\nmethod. This method takes a\n[`ScanCallback`](/reference/android/bluetooth/le/ScanCallback) as a parameter.\nYou must implement this callback, because that is how scan results are returned.\nBecause scanning is battery-intensive, you should observe the following\nguidelines:\n\n- As soon as you find the desired device, stop scanning.\n- Never scan on a loop, and always set a time limit on your scan. A device that was previously available may have moved out of range, and continuing to scan drains the battery.\n\nIn the following example, the BLE app provides an activity\n(`DeviceScanActivity`) to scan for available Bluetooth LE devices and display\nthem in a list to the user. The following snippet shows how to start and stop a\nscan: \n\n### Kotlin\n\n```kotlin\nprivate val bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner\nprivate var scanning = false\nprivate val handler = Handler()\n\n// Stops scanning after 10 seconds.\nprivate val SCAN_PERIOD: Long = 10000\n\nprivate fun scanLeDevice() {\n if (!scanning) { // Stops scanning after a pre-defined scan period.\n handler.postDelayed({\n scanning = false\n bluetoothLeScanner.stopScan(leScanCallback)\n }, SCAN_PERIOD)\n scanning = true\n bluetoothLeScanner.startScan(leScanCallback)\n } else {\n scanning = false\n bluetoothLeScanner.stopScan(leScanCallback)\n }\n}\n```\n\n### Java\n\n```java\nprivate BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();\nprivate boolean scanning;\nprivate Handler handler = new Handler();\n\n// Stops scanning after 10 seconds.\nprivate static final long SCAN_PERIOD = 10000;\n\nprivate void scanLeDevice() {\n if (!scanning) {\n // Stops scanning after a predefined scan period.\n handler.postDelayed(new Runnable() {\n @Override\n public void run() {\n scanning = false;\n bluetoothLeScanner.stopScan(leScanCallback);\n }\n }, SCAN_PERIOD);\n\n scanning = true;\n bluetoothLeScanner.startScan(leScanCallback);\n } else {\n scanning = false;\n bluetoothLeScanner.stopScan(leScanCallback);\n }\n}\n```\n| **Note:** The [`BluetoothLeScanner`](/reference/android/bluetooth/le/BluetoothLeScanner) is only available from the [`BluetoothAdapter`](/reference/android/bluetooth/BluetoothAdapter) if Bluetooth is currently enabled on the device. If Bluetooth is not enabled, then [`getBluetoothLeScanner()`](/reference/android/bluetooth/BluetoothAdapter#getBluetoothLeScanner()) returns null.\n\nTo scan for only specific types of peripherals, you can instead call\n[`startScan(List\u003cScanFilter\u003e, ScanSettings, ScanCallback)`](/reference/android/bluetooth/le/BluetoothLeScanner#startScan(java.util.List%3Candroid.bluetooth.le.ScanFilter%3E,%20android.bluetooth.le.ScanSettings,%20android.bluetooth.le.ScanCallback)),\nproviding a list of [`ScanFilter`](/reference/android/bluetooth/le/ScanFilter)\nobjects that restrict the devices that the scan looks for and a\n[`ScanSettings`](/reference/android/bluetooth/le/ScanSettings) object that\nspecifies parameters about the scan.\n\nThe following code sample is an implementation of\n[`ScanCallback`](/reference/android/bluetooth/le/ScanCallback),\nwhich is the interface used to deliver BLE scan results. When results are found,\nthey are added to a list adapter in the `DeviceScanActivity` to display to the\nuser. \n\n### Kotlin\n\n```kotlin\nprivate val leDeviceListAdapter = LeDeviceListAdapter()\n// Device scan callback.\nprivate val leScanCallback: ScanCallback = object : ScanCallback() {\n override fun onScanResult(callbackType: Int, result: ScanResult) {\n super.onScanResult(callbackType, result)\n leDeviceListAdapter.addDevice(result.device)\n leDeviceListAdapter.notifyDataSetChanged()\n }\n}\n```\n\n### Java\n\n```java\nprivate LeDeviceListAdapter leDeviceListAdapter = new LeDeviceListAdapter();\n\n// Device scan callback.\nprivate ScanCallback leScanCallback =\n new ScanCallback() {\n @Override\n public void onScanResult(int callbackType, ScanResult result) {\n super.onScanResult(callbackType, result);\n leDeviceListAdapter.addDevice(result.getDevice());\n leDeviceListAdapter.notifyDataSetChanged();\n }\n };\n```\n| **Note:** You can only scan for Bluetooth LE devices *or* scan for classic Bluetooth devices, as described in [Bluetooth overview](/develop/connectivity/bluetooth). You can't scan for both Bluetooth LE and classic devices at the same time."]]