Change the Android bluetooth device name

后端 未结 3 2051
忘了有多久
忘了有多久 2020-12-05 11:40

I know it\'s possible to get the local device name as described in the solution to this question Display Android Bluetooth Device Name

What I\'m interested in knowin

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 12:04

    To change the bluetooth name properly you need to take care of following things:

    1) You need following permissions: android.permission.BLUETOOTH android.permission.BLUETOOTH_ADMIN

    2) Check the bluetooth state from adapter as you can only change the name of bluetooth is turned on.

    val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if(bluetoothAdapter.state == BluetoothAdapter.STATE_ON){
       bluetoothAdapter.setName("NewDeviceName");
    }
    

    3) If the bluetooth is not turned on then you can turn it on with the following command:

    bluetoothAdapter.enable()
    

    4) Last thing, please don't use static timers to wait for bluetooth state changes instead the proper way is that you can register for android.bluetooth.adapter.action.STATE_CHANGED broadcast and useBluetoothAdapter.EXTRA_STATE to get the new state of bluetooth whenever it is changed.

    Note: Not all devices behave the same when it comes to bluetooth and changing the name due to caching and hw address, so never expect same outcome from all devices.

提交回复
热议问题