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);
}
}
can someone help me out?
Also I've noticed that now Google is requiring also permission to post notifications. I've already added the permission in the manifest file but I would still need help in handling the request permission. In my service I get the following line in red (issue):
this.notificationManager.notify(notificationID, notification);
because:
Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException
And this is the suggested fix by the IDE:
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Does this mean I need to check for permissions every time I send a notification or this only appears because I have not checked/requested for permission in the main activity or when I started the service?
First, This is a sample code for using
ActivityResultContractwhich matches your use case.Also, you can check this documentation.
Second, I recommend you check permission when you send a notification.
Even though a user allowed your app's notification permission in your application entry points like MainActivity or a service, Users can change the permission in the system setting whenever they want.
So it's a developer's responsibility to be ready for this scenario.