'Possible? Android Permission Request Concurrency Issue

Is there a possibility that the below code could fail due to the user denying the SCHEDULE_EXACT_ALARM permission after the permissions check and before the alarm is scheduled?

Note: I have never experienced this issue, this is purely an academic excersize.

public class MyService extends Service {

    private void scheduleExactAlarm(Calendar alarmCalendar) {

        if(getApplicationContext().checkSelfPermission(Manifest.permission.SCHEDULE_EXACT_ALARM) != PackageManager.PERMISSION_GRANTED) {
            // handle permission not granted
            return;
        }

        // can the user deny the permission here?

        AlarmManager.AlarmClockInfo alarmInfo = // create alarmInfo with desired information
        PendingIntent alarmOperation = // create alarmOperation with desired intent    
        AlarmManager alarmManager = getSystemService(AlarmManager.class);    
        alarmManager.setAlarmClock(alarmInfo, alarmOperation);
    }
    
    // the rest of the service implementation...

}

EDIT: I learned something new today. Special Permissions are not part of runtime permissions, so using checkSelfPermission(SCHEDULE_EXACT_ALARM) doesn't make sense. That being said, the question is intended to be broader than the specific permissions/operations used.



Solution 1:[1]

No, it is not possible. Android will terminate your process if Android revokes a permission for any reason (user revoked it in Settings, auto-revocation due to lack of app use on Android 12+, etc.).

That being said, Ian Lake's comment is also valid: checkSelfPermission(Manifest.permission.SCHEDULE_EXACT_ALARM) should never return PERMISSION_GRANTED is not going to work well. While your concern is valid for dangerous permissions, based on current 13 DP1 behavior, SCHEDULE_EXACT_ALARM is not categorized as dangerous and is not part of the runtime permission system.

Solution 2:[2]

Theoretically? Sure, if the OS decided to task switch taking the processor away from the app, and the user denied permission before it task switched back. Practically? No, task switches happen many times a second, there's no way it wouldn't get a time slice before a user would do that.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Gabe Sechan