Skip to content

Deprecated method “startActivityForResult()” vs properly bluetooth set up

Hey I try to make bluetooth service according to the information on the official android dev website. But I came across to the deprecate method startActivityForResult(). What should I do to properly turn on bluetooth device?

Here is my code with deprecated method:

private void enableBt(View view){
        if(myBluetoothAdapter==null){
            //we don't have bt in this device
        }
        else if(!myBluetoothAdapter.isEnabled()){
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

    }

Answer

It’s a special AndroidX extension that wraps the startActivityForResult and provide sort of a simpler method.

According to Android Developers, you need to extend ActivityResultContract, in which you implement an input/output for the activity result call by overriding 2 methods:

  1. Method for creating intent based on the input.
  2. Method for parsing an output based on the activity result.

In your case you don’t have an input so you can use Void type for the input (don’t know about your output though).

After properly implementing that contract class, you simply create an instance from that class and pass it to registerForActivityResult(…) (before your activity is started), which returns some sort of a launcher.

You use that launcher and call launch instead of startActivityForResult.

Enjoy 🙂