Change the Android bluetooth device name

后端 未结 3 2045
忘了有多久
忘了有多久 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

    Thanks for the original answer, here are a few things I found when implementing that might help someone else out.

    1) BT has to be enabled for setName() to work.

    2) It takes time for BT to Enable. ie. you Can't just call enable() then setName()

    3) It takes time for the name to "sink in". ie. you can't call getName() right after setName() and expect the new name.

    So, here is a snippet of code I came up with to use a runnable to get the job done in the background. It is also time bound to 10seconds, so it won't run forever if there is a problem.

    Finally, this is part of our power on check, and we normally leave BT disabled (due to battery). So, I turn BT back off after, you may not want to do that.

    // BT Rename
    //
    final String sNewName = "Syntactics";
    final BluetoothAdapter myBTAdapter = BluetoothAdapter.getDefaultAdapter();
    final long lTimeToGiveUp_ms = System.currentTimeMillis() + 10000;
    if (myBTAdapter != null)
    {
        String sOldName = myBTAdapter.getName();
        if (sOldName.equalsIgnoreCase(sNewName) == false)
        {
            final Handler myTimerHandler = new Handler();
            myBTAdapter.enable();
            myTimerHandler.postDelayed(
                    new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            if (myBTAdapter.isEnabled())
                            {
                                myBTAdapter.setName(sNewName);
                                if (sNewName.equalsIgnoreCase(myBTAdapter.getName()))
                                {
                                    Log.i(TAG_MODULE, "Updated BT Name to " + myBTAdapter.getName());
                                    myBTAdapter.disable();
                                }
                            }
                            if ((sNewName.equalsIgnoreCase(myBTAdapter.getName()) == false) && (System.currentTimeMillis() < lTimeToGiveUp_ms))
                            {
                                myTimerHandler.postDelayed(this, 500);
                                if (myBTAdapter.isEnabled())
                                    Log.i(TAG_MODULE, "Update BT Name: waiting on BT Enable");
                                else
                                    Log.i(TAG_MODULE, "Update BT Name: waiting for Name (" + sNewName + ") to set in");
                            }
                        }
                    } , 500);
        }
    }
    

提交回复
热议问题