Home > Software engineering >  Android Studio: change from startActivityForResult to registerForActivityResult
Android Studio: change from startActivityForResult to registerForActivityResult

Time:04-25

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");
                }
            }
        });

CodePudding user response:

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

launcher.launch(intent)

CodePudding user response:

For those who need's in Java can use

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

        });


startForResult.launch(intent);
  • Related