0

I'm following developer android tutorial about Bluetooth and when it comes to configuration part, it says that the following code must be used

if (!bluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

but it says that startActivityForResult is deprecated and I have no clue how it could be changed .

I tried using registerForActivityResult but I don`t know very well how it works.

lr_04
  • 1

1 Answers1

1

You can do it this way Note: this code is in KOTLIN JAVA version is also below it

Declare variable

var launchData: ActivityResultLauncher<Intent>? = null

instead of onActivityResult, in onCreate mention before opening new Activity

launchData =
 registerForActivityResult(ActivityResultContracts.StartActivityForResult())
            {
                if (it.resultCode == Activity.RESULT_OK) {
                    if (it.data != null) {
                        it.data.let { obj ->
                           var detail =   obj?.getStringExtra("details")
                                 // or whatever your result keys are
                        }
                    }
                }
            }

instead of startActivityForResult

Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE).also {
                launchData!!.launch(it)
            }

JAVA

Variable Declaration

ActivityResultLauncher<Intent> launchData = null;

in onCreate

launchData= registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == Activity.RESULT_OK) {
                            // There are no request codes
                            Intent data = result.getData();
                            data.getStringExtra("details");
                        }
                    }
                });

result callback

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        launchData.launch(enableBtIntent);
Kartik Agarwal
  • 1,129
  • 1
  • 8
  • 27