0

I am trying to change the name of the Android Device that my program that is currently running on because the name of the device will contain information that is relevant when it communicates with other phones. The name of the phone will be constantly changed as phone scans for other phones and calculates information. Any ideas on how to change the name of the phone within the java code? I can't image it being more than a few lines of code, but I can't find anything. Thanks in advance.

1

1 Answer 1

1

It's quite easy, get an instance of the bluetooth adaptor (since the only name you can set is the bluetooth name I think) that refers to the local device and call setName("newName"); on it.

BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
                 myDevice.setName("new name");

Quoting the docs:

Valid Bluetooth names are a maximum of 248 bytes using UTF-8 encoding, although many remote devices can only display the first 40 characters, and some may be limited to just 20.

So be careful with what you set as the device name. Oh, on another note, you can't change the name if the device bluetooth is off. So the actual code after checking it would be something on the lines of the following:

BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
if(myDevice.getState() == BluetoothAdapter.STATE_ON){
    myDevice.setName("new name");
}

Important to note: If you are going to test this on an emulator, beware that there are not bluetooth capabilities on the emulators and therefor the getDefaultAdapter() method returns null, resulting in a NullPointerException :)

Sign up to request clarification or add additional context in comments.

4 Comments

Yeah i forgot to mention that it was bluetooth, but this appears to be correct. I will try it out later when I have the opportunity and let you know if you were correct. Thanks so much.
@user1153018 Don't forget to +1 and accept if it's what your after. Check the updated version for the complete code, including a state check to ensure the adapter is on.
I will accept it if it is the answer and I don't have a high enough rep yet to +1 your answer.
It will not update in android 13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.