I am extending support to an old app to Android 13 and I am seeing a lot of changes.
First off, I've noticed that startActivityForResult is deprecated since Google decided to change how to handle permission requests and results.
Here there are few examples: OnActivityResult method is deprecated, what is the alternative? but honestly I did quite catch how the new way works. Only got that it seems that uses an Observer pattern.
This is how I am currently asking for overlay permissions:
private void askForSystemOverlayPermission() {
if (!Settings.canDrawOverlays(this)) {
//If the draw over permission is not available open the settings screen
//to grant the permission.
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, DRAW_OVER_OTHER_APP_PERMISSION_REQUEST_CODE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DRAW_OVER_OTHER_APP_PERMISSION_REQUEST_CODE) {
if (!Settings.canDrawOverlays(this)) {
//Permission is not available. Display error text.
errorToastDrawOverOtherApp();
finish();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
This is how I've updated my code:
ActivityResultLauncher<Intent> activityResultLaunch = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
System.out.println("Code:"+result.getResultCode());
if (result.getResultCode() == RESULT_CODE_1) {
// ToDo : Do your stuff...
} else if(result.getResultCode() == RESULT_CODE_2) {
// ToDo : Do your stuff...
}
}
});
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
activityResultLaunch.launch(intent);
}
but like mentioned I am getting always a result = 0. What I am doing wrong?
You are using
startActivityForResult(). ThatIntentaction is not documented to return a result.That
Intentaction is not documented to return a result, so0is the expected value.If you are expecting something akin to
DRAW_OVER_OTHER_APP_PERMISSION_REQUEST_CODEfrom your earlier code, that is not howActivityResultContractsworks.DRAW_OVER_OTHER_APP_PERMISSION_REQUEST_CODEis a request code, not a result code. And, you will note that you are not supplying a request code, because that is handled internally byActivityResultContracts.StartActivityForResult.