Android Studio: change from startActivityForResult to registerForActivityResult

1k Views Asked by At

How would I change from startActivityForResult to registerForActivityResult for this Bluetooth activity? Please help me as I am new to java and Android Studio. I have tried watching videos and tutorials but I only get more errors. Any tips you can give me would be greatly appreciated.

        //on btn click
        mOnBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBlueAdapter.isEnabled()){
                    showToast("Turning On Bluetooth...");
                    //intent to on bluetooth
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(intent, REQUEST_ENABLE_BT);
                }
                else {
                    showToast("Bluetooth is already on");
                }
            }
        });

2

There are 2 best solutions below

0
On
private val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
    if (result.resultCode == Activity.RESULT_OK) {
    
    }
}

launcher.launch(intent)
0
On

For those who need's in Java can use

private ActivityResultLauncher<Intent> startForResult =
        registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {

        });


startForResult.launch(intent);