android BluetoothDevice.getName() gibt null zurück - ViResist (2023)

Lesezeit: 7 Minuten

android BluetoothDevice.getName() gibt null zurück - ViResist (1)
maonanyue

Irgendwann gibt BluetoothDevice.getName() null zurück. Wie kann ich es reparieren? remoteDeviceName kann im folgenden Code null sein. Und ich muss mein Gerät und andere Geräte nach remoteDeviceName unterscheiden.

BluetoothAdapter.getDefaultAdapter().startLeScan(new LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) { String remoteDeviceName = device.getName(); Log.d("Scanning", "scan device " + remoteDeviceName); });
  • Warum machst du keine Nullprüfung?

    – Niko Adrianus Yuwono

    10. Oktober 14 um 2:37 Uhr

  • Natürlich kann ich prüfen, ob es null ist. Aber Nullname ist für mich nutzlos. Und es ist nicht null, also gibt es eine API, um den Gerätenamen zu aktualisieren?

    – maonanyue

    10. Oktober 14 um 2:41 Uhr


android BluetoothDevice.getName() gibt null zurück - ViResist (2)
maonanyue

Endlich habe ich die Lösung herausgefunden:

1.Für angeschlossenes Gerät:

Gerätename aus gatt-Merkmal lesen org.bluetooth.characteristic.gap.device_name Nutzungsbedingungen, Geschäftsbedingungen org.bluetooth.service.generic_access.

2. Für kein angeschlossenes Gerät:

 /** * Get device name from ble advertised data */ private LeScanCallback mScanCb = new LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) { final BleAdvertisedData badata = BleUtil.parseAdertisedData(scanRecord); String deviceName = device.getName(); if( deviceName == null ){ deviceName = badata.getName(); } }////////////////////// Helper Classes: BleUtil and BleAdvertisedData /////////////// final public class BleUtil { private final static String TAG=BleUtil.class.getSimpleName(); public static BleAdvertisedData parseAdertisedData(byte[] advertisedData) { List<UUID> uuids = new ArrayList<UUID>(); String name = null; if( advertisedData == null ){ return new BleAdvertisedData(uuids, name); } ByteBuffer buffer = ByteBuffer.wrap(advertisedData).order(ByteOrder.LITTLE_ENDIAN); while (buffer.remaining() > 2) { byte length = buffer.get(); if (length == 0) break; byte type = buffer.get(); switch (type) { case 0x02: // Partial list of 16-bit UUIDs case 0x03: // Complete list of 16-bit UUIDs while (length >= 2) { uuids.add(UUID.fromString(String.format( "%08x-0000-1000-8000-00805f9b34fb", buffer.getShort()))); length -= 2; } break; case 0x06: // Partial list of 128-bit UUIDs case 0x07: // Complete list of 128-bit UUIDs while (length >= 16) { long lsb = buffer.getLong(); long msb = buffer.getLong(); uuids.add(new UUID(msb, lsb)); length -= 16; } break; case 0x09: byte[] nameBytes = new byte[length-1]; buffer.get(nameBytes); try { name = new String(nameBytes, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } break; default: buffer.position(buffer.position() + length - 1); break; } } return new BleAdvertisedData(uuids, name); } } public class BleAdvertisedData { private List<UUID> mUuids; private String mName; public BleAdvertisedData(List<UUID> uuids, String name){ mUuids = uuids; mName = name; } public List<UUID> getUuids(){ return mUuids; } public String getName(){ return mName; } }
  • Wie erhalten Sie den Gerätenamen aus der Gatt-Eigenschaft? kannst du mir ein beispiel geben

    – Yazhini Murugaiya

    20. April 16 um 08:27 Uhr

  • Die bereitgestellten Links funktionieren nicht. Können Sie das bitte überprüfen? @maonanyue

    – MSD

    28. August 19 um 6:00 Uhr

  • Was genau meinst du mit “Gerätename aus Gatt-Merkmal org.bluetooth.characteristic.gap.device_name of service org.bluetooth.service.generic_access lesen”.

    – El Sushiboi

    25. Februar 20 um 17:13 Uhr

  • Sobald die Verbindung hergestellt ist, sollten Sie die Diensterkennung durchführen, und dann wird das Merkmal des Gerätenamens in BluetoothGatt im Generic Access-Dienst vorhanden sein. Dieser Dienst wird ebenso wie der Merkmalseintrag DeviceName benötigt. Ich kann jedoch keinen Code in einem Kommentar posten.

    – Brian Reinhold

    19. November 21 um 14:28 Uhr

BluetoothDevice.getName() kann zurückkehren null wenn der Name nicht ermittelt werden konnte. Dies kann auf eine Reihe von Faktoren zurückzuführen sein. Unabhängig davon ist der Name freundlich Name des Geräts und sollte nicht verwendet werden, um es von anderen Geräten zu unterscheiden. Verwenden Sie stattdessen die Hardwareadresse durch getAddress().

  • Benutzer können die Bluetooth-Adresse in unserem BLE-Gerät (Uhr usw.) nicht sehen und kennen nur den Bluetooth-Namen des Geräts. Wenn also getName() null zurückgibt, ist es ein Problem, das genaue Gerät zum Verbinden auszuwählen.

    – maonanyue

    10. Oktober 14 um 5:56 Uhr

Ich weiß, dass dies alt ist, aber diese eher spezifikationsorientierte Antwort kann bei der Beantwortung einiger Fälle hilfreich sein.

Bei Bluetooth Low Energy sind Ankündigungs- und Scanantwortdaten nur erforderlich, um die Bluetooth-Adresse zu haben. Ankündigungsdaten sind, wie ein Client-BTLE-Endpunkt ein Dienstgerät erkennt. Ein Client kann eine Scan-Antwort anfordern und mehr Daten erhalten. Der Gerätename ist in diesen Daten optional. Die BTLE-Spezifikation erfordert jedoch, dass alle Bluetooth Low Energy-Endpunkte den generischen Zugriffsdienst unterstützen, der zur Unterstützung der Gerätenamenseigenschaft erforderlich ist. Um diese Eigenschaft zu lesen, muss das Android leider zuerst eine Verbindung herstellen und die Diensterkennung durchführen. Wenn die Anzeige/Scan-Antwort die Informationen nicht liefert, glaube ich nicht, dass Android eine Verbindung zum Gerät herstellt, um den Namen zu erhalten. Zumindest habe ich noch nie einen Hinweis auf eine Verbindung gesehen, ohne dass die App ausdrücklich eine Verbindung angefordert hat. Dies ist nicht das, was Sie tun möchten, wenn Sie sich für eine Verbindung entscheiden möchten.

Glücklicherweise geben die meisten BTLE-Geräte, mit denen ich gearbeitet habe, ihren Namen in der Anzeige oder Scan-Antwort an.

Eine andere Möglichkeit besteht darin, dass das Gerät den Namen in den Scan-Antwortteil der Ankündigung einfügt. Je nachdem, wie man den BTLE-Scanner von Android eingerichtet hat, erhält man möglicherweise nur die Werbedaten und nicht die Scan-Antwort. In diesem Fall wird der Name nicht gefunden, wenn das Gerät ihn in die Scan-Antwort einfügt. Die standardmäßigen Scannereinstellungen sind jedoch so, dass eine Scanantwort empfangen werden muss, bevor die Scandaten an die App weitergeleitet werden.

    android BluetoothDevice.getName() gibt null zurück - ViResist (3)
    Kevin

    Verwenden Sie auf Marshmallow ScanRecord.getDeviceName() um den in den Scan-Datensatz eingebetteten lokalen Namen abzurufen.

    BluetoothDevice.getName() ist unzuverlässig, wenn der lokale Name in einer Scan-Antwort statt im unmittelbaren Ankündigungspaket enthalten ist.

     @Override public void onScanResult(int callbackType, ScanResult scanResult) { super.onScanResult(callbackType, scanResult); // Retrieve device name via ScanRecord. String deviceName = scanResult.getScanRecord().getDeviceName(); }

    android BluetoothDevice.getName() gibt null zurück - ViResist (4)
    Etrusker

    Ich habe versucht, den Namen meines RN4020 Bluetooth-Moduls anzuzeigen und hatte das gleiche Problem. Habe das Problem im Forum von Microchip gefunden:

    Wenn Sie den privaten Dienst oder MLDP aktiviert haben, beträgt die maximale Byteanzahl des Gerätenamens 6 Byte, aufgrund der 31-Byte-Nutzlastbeschränkung für Werbung.

    Ich hatte den Gerätenamen auf 9 Zeichen gesetzt. Das Festlegen des Namens auf 4 Bytes hat das Problem behoben.

    Wenn Sie die UUIDs Ihrer benutzerdefinierten Dienste erkennen, damit Sie wissen, dass es sich um Ihr Gerät handelt, können Sie sich auch mit dem Gerät verbinden und seinen Namen lesen (wenn er in meinem Fall länger als 6 Bytes ist). Dies wurde auch im Microchips-Forum vorgeschlagen.

    http://www.microchip.com/forums/m846328.aspx

      android BluetoothDevice.getName() gibt null zurück - ViResist (5)
      Tunji_D

      Ich habe festgestellt, dass, wenn Sie den Namen des Geräts unmittelbar nach dem Abholen beim Scannen abfragen, möglicherweise null zurückgegeben wird. Um dies zu umgehen, frage ich ungefähr jede Sekunde ein Runnable auf dem UI-Thread ab, maximal 3 Mal (also 3 Sekunden), und der Name wird normalerweise bis dahin aufgelöst.

      Beachten Sie, dass im bereitgestellten Snippet die einschließende Klasse implementiert Runnable, daher kann ich bestehen this hinein View.postDelayed(Runnable action, long delayMillis)

       private static final int MAX_NAME_CHECKS = 3; private static final int NAME_CHECK_PERIOD = 1000; int nameChecks; @Override public void run() { resolveName(); } /** * Checks for the device name, for a maximum of {@link ViewHolder#MAX_NAME_CHECKS} * as the name may not have been resolved at binding. */ private void resolveName() { if (device != null) { String name = device.getName(); boolean isEmptyName = TextUtils.isEmpty(name); if (isEmptyName) deviceName.setText(R.string.unknown_device); else deviceName.setText(name); // Check later if device name is resolved if (nameChecks++ < MAX_NAME_CHECKS && isEmptyName) itemView.postDelayed(this, NAME_CHECK_PERIOD); } }

        android BluetoothDevice.getName() gibt null zurück - ViResist (6)
        Gallgall

        Denn jemand hat die Lösung nicht gefunden.

        1. Das Bluetooth-Anzeigenpaket hat eine maximale Größe von 31 Byte. Wenn Ihr Gerät also einen langen Namen hat. Es kann abgeschnitten werden. Sehen: https://devzone.nordicsemi.com/f/nordic-qa/14/what-s-the-maximum-size-for-an-advertisement-package

        2. Wenn Sie den korrekten Namen des Bluetooth-Geräts (auch langer Name) erhalten möchten, verwenden Sie ihn bitte nicht startLeScan(). Stattdessen Methode verwenden startDiscovery(). Google sagte: “Der Erkennungsprozess umfasst normalerweise einen Abfragescan von etwa 12 Sekunden, gefolgt von einem Seitenscan jedes gefundenen Geräts, um seinen Bluetooth-Namen abzurufen.” Ich habe es versucht und es funktioniert wie ein Zauber. Sehen: https://developer.android.com/guide/topics/connectivity/bluetooth

          .

          5022200cookie-checkandroid BluetoothDevice.getName() gibt null zurück

          #Android #Bluetooth #Gerät #Netzwerk-Scan #Null

          FAQs

          How to get Bluetooth device name in android programmatically? ›

          Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken text view to show Bluetooth name.

          How do I find an unknown Bluetooth device? ›

          To find an active Bluetooth device, first make sure you have Bluetooth enabled on your smartphone. Next, download Wunderfind for your iPhone or Android device and launch the app. Immediately, you'll see a list of Bluetooth devices that your smartphone has detected using its built-in Bluetooth radio.

          How do I recover an unpaired Bluetooth device that I deleted? ›

          Step 1: Go to Settings on your device and then click System. Step 2: Choose the option of Reset Wi-Fi, Mobile, and Bluetooth and then confirm the choice in the next window. Step 3: You may be asked to enter your password to start the process. Step 4: After the reset, you can reconnect the device.

          How do I pair a previously unpaired Bluetooth device? ›

          Make sure Bluetooth is turned on. Touch and hold Bluetooth . In the list of paired devices, tap a paired but unconnected device. When your phone and the Bluetooth device are connected, the device shows as "Connected."

          Is there a way to track Bluetooth devices? ›

          Bluetooth Radar can detect all nearby devices. Find and select your lost device on the list, then move around slowly and keep watching the signal strength, estimated distance, and hints on the screen. When it reads "Your Device Is Here!", please look around. You should find your device nearby.

          What is the UUID of a Bluetooth device? ›

          The UUID stands for Universally Unique Identifier. UUID is an simple 128 bit digit which uniquely distributed across the world. Bluetooth sends data over air and all nearby device can receive it. Let's suppose, sometimes you have to send some important files via Bluetooth and all near by devices can access it in range.

          How do I find an unknown device? ›

          A simple way to identify an "unknown device on a network" is through the command-line interface (CLI) of your computer system. Operating systems such as Windows, Linux, and macOS have their own set of networking commands such as "ipconfig" and “ping” for basic scanning and troubleshooting.

          What to do if Bluetooth is hidden in Device Manager? ›

          Show Hidden Devices

          To check for hidden devices, launch Device Manager and open the View menu. There, click Show hidden devices and check if Bluetooth is now visible.

          Can someone connect to Bluetooth without me knowing? ›

          Yes, Bluetooth can be hacked. While using this technology has offered a lot of creature comforts, it has also exposed people to cyberattacks. Almost all devices are Bluetooth enabled—from smartphones to cars.

          How do I reinstall Bluetooth drivers after uninstalling? ›

          We recommend you reboot your PC once after uninstalling the driver. Step 6: To reinstall the Bluetooth driver, simply navigate to Windows 10 Settings app > Update & Security > Windows Update page and then click the Check for updates button. Windows 10 will automatically download and install the Bluetooth driver.

          How do I recover deleted Bluetooth files on Android? ›

          Run Google app on your Android phone and sign in your Google account. Click Settings. As you see Personal, choose the option Backup & Restore. Finally, click Automatic Restore and recover deleted files from Android.

          How do I reinstall Bluetooth devices? ›

          Install Bluetooth driver manually summary
          1. Open Settings.
          2. Click on Update & Security.
          3. Click on Windows Update.
          4. Click the Check for updates button (if applicable).
          5. Click the View optional updates option.
          6. Click the Driver updates tab.
          7. Select the driver you want to update.
          8. Click the Download and install button.

          How do I reset my paired devices? ›

          Step 1: Clear devices from your phone's memory
          1. Open your phone's Settings app.
          2. Tap Connected devices. Previously connected devices. ...
          3. If you see devices you're not currently using, next to each device name, tap Settings Forget. ...
          4. If you paired your phone and car before, next to your car's name, tap Settings Forget.

          How to connect Bluetooth which is already connected with another device? ›

          Turn off the Bluetooth speaker and then turn it back on. On the device you want to connect to the speaker, go to the Bluetooth settings and search for available devices. Select the Bluetooth speaker from the list of available devices and connect to it.

          How to scan Bluetooth devices in Android programmatically? ›

          BluetoothAdapter adapter = BluetoothAdapter. getDefaultAdapter(); To start discover, simply call the startDiscovery() from bluetooth adapter. This process is asynchronous so it will return immediately.

          Is there an app to find all Bluetooth devices? ›

          Designed for Android version 4.4+. Bluetooth Device Find & Locate is FREE to download. Now easily find any type of Bluetooth devices. In case you cannot find your Bluetooth device use this app to locate it.

          What is elk bledom used for? ›

          ELK-BLEDOM Is a Bluetooth LED Strip Light

          If you see ELK-BLEDOM in the Bluetooth connection list on any device (such as an iPhone, Android smartphone, PC, Mac, or otherwise), chances are very high that someone nearby has a smart LED strip light plugged in.

          What is the code used in Bluetooth? ›

          In Bluetooth, each baseband packet starts with an Access code, which can be one of 3 types: CAC (Channel Access Code), DAC (Device Access Code) and IAC (Inquiry Access Code). The respective access code types are used for a Bluetooth unit in different operating modes. The CAC (Channel Access Code) identifies a piconet.

          How do I find the IP address of my Bluetooth device? ›

          Retrieve Bluetooth Address for Windows

          Click the Hardware menu, and then click Properties. Click the Details menu, and then select the Property as Bluetooth Device Address . The Value is the Bluetooth address of the device.

          What is GATT in Bluetooth? ›

          Just as the GAP layer handles most connection-related functionality, the GATT layer of the Bluetooth low energy protocol stack is used by the application for data communication between two connected devices.

          What is the unknown device in Device Manager? ›

          The main reason for Unknown Device to display in your Device Manager is because you have a device that is not working correctly. To fix this issue, obtain an updated driver for the device. Use the following methods to enable Windows to recognize your device.

          How do I identify an unknown USB device? ›

          Locate any hardware devices that are reported to be unrecognized (may be indicated by a yellow ! icon, or something similar), right-click the device, and select Properties. Select the Details tab. View the plug-and-play Hardware ID information in the Property selection list.

          How do I enable hidden devices? ›

          To include hidden devices in Device Manager display, select View and select Show hidden devices.

          How do I connect to a hidden Bluetooth? ›

          When you do have Bluetooth enabled, make sure it is “hidden,” not “discoverable.” The hidden mode prevents other Bluetooth devices from recognizing your device. This does not prevent you from using your Bluetooth devices together. You can “pair” devices so that they can find each other even if they are in hidden mode.

          Can Bluetooth be spied on? ›

          While some devices use a level of Bluetooth encryption that can protect your devices and data, others operate on open frequencies. If hackers can intercept (or hack) your connection, they can also intercept data (such as passwords and credit card numbers), take over your devices, or spy on you.

          How do I get Bluetooth hidden icons? ›

          Go to Start > Settings > Devices > More Bluetooth options. On the Bluetooth Settings screen, select Show the Bluetooth icon in the notification area.

          What to do if Bluetooth name is not showing? ›

          Step 1: Check Bluetooth basics
          1. Turn Bluetooth off and then on again. Learn how to turn Bluetooth on and off.
          2. Confirm that your devices are paired and connected. Learn how to pair and connect via Bluetooth.
          3. Restart your devices. Learn how to restart your Pixel phone or Nexus device.

          How do I find my Android device name? ›

          Open the Settings app to check your device information:
          1. Tap About phone.
          2. Take note of your device name.
          Mar 27, 2023

          Where is Bluetooth listed in Device Manager? ›

          Run the Bluetooth Troubleshooter

          If Bluetooth is still missing from Device Manager, you should use the built-in Bluetooth troubleshooter to fix the problem. Press Windows key + I to bring up Windows Settings. Go to System > Troubleshoot > Other trouble-shooters. From the Other list, click Run next to Bluetooth.

          How do I read my Bluetooth address? ›

          Bluetooth Address is usually displayed as 6 bytes written in hexadecimal and separated by colons (example - 00:11:22:33:FF:EE).

          References

          Top Articles
          Latest Posts
          Article information

          Author: Jonah Leffler

          Last Updated: 10/25/2023

          Views: 6460

          Rating: 4.4 / 5 (65 voted)

          Reviews: 80% of readers found this page helpful

          Author information

          Name: Jonah Leffler

          Birthday: 1997-10-27

          Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

          Phone: +2611128251586

          Job: Mining Supervisor

          Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

          Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.