skip to Main Content

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

Answers


  1. private val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        if (result.resultCode == Activity.RESULT_OK) {
        
        }
    }
    
    launcher.launch(intent)
    
    Login or Signup to reply.
  2. For those who need’s in Java can use

    private ActivityResultLauncher<Intent> startForResult =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
    
            });
    
    
    startForResult.launch(intent);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search