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 Answers
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
:)

- 20,634
- 8
- 68
- 91
-
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. – johns4ta May 10 '12 at 17:48
-
@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. – Juan Cortés May 10 '12 at 17:50
-
I will accept it if it is the answer and I don't have a high enough rep yet to +1 your answer. – johns4ta May 10 '12 at 17:52