Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
I was requesting to start Bluetooth using above source code. But, startActivityForResult
is deprecated. So, I was searching for new code how to deal with that. Here's the solution I found.
// You can do the assignment inside onAttach or onCreate, i.e, before the activity is displayed
ActivityResultLauncher<Intent> someActivityResultLauncher = 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();
doSomeOperations();
}
}
});
public void openSomeActivityForResult() {
Intent intent = new Intent(this, SomeActivity.class);
someActivityResultLauncher.launch(intent);
}
I added it to my source code.
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
ActivityResultLauncher<Intent> someActivityResultLauncher = 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();
// doSomeOperations();
}
}
});
someActivityResultLauncher.launch(enableBtIntent);
But, Android is requesting for bluetooth permission automatically for old source code (I didn't have to add onActivityResult function. Cause, it was earlier written in background). But, when I am using ActivityResultLauncher I must add onActivityResult function(I can work without onActivityResult also But, startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
I had sent an integer value also REQUEST_ENABLE_BT=1
). How can I request for bluetooth permission with new code?