androidkotlinfirebase-cloud-messaging

How to provide ActivityCompat.requestPermissions with MainActivity in Android using Kotlin


I'm trying to integrate notifications with my app. Following google official documentation there's two ways to handle a notification. One is in the system tray to which the app will simply be launched by the system using launcher. The other is when the data of the notification needs to be processed by the app. I'm tackling the later.

I'm stuck at finding a way to provide MainActivity (class MainActivity : ComponentActivity()) as activity parameter to ActivityCompat.requestPermissions() as well as ActivityCompat.shouldShowRequestPermissionRationale().

Code is of the following:

if (ActivityCompat.checkSelfPermission(
            context,
            Manifest.permission.POST_NOTIFICATIONS
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        if (!ActivityCompat.shouldShowRequestPermissionRationale(
                MainActivity, Manifest.permission.POST_NOTIFICATIONS)) {
            ActivityCompat.requestPermissions(
                MainActivity,
                arrayOf(Manifest.permission.POST_NOTIFICATIONS),
                1000
            )
        }
        // 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
    }

where MainActivity gives an error:

Type mismatch.
Required: Activity
Found: MainActivity.Companion

I presume this is old clunk coming from previous installments regarding development on Android? Otherwise, I simply don't understand how you can have people rely on mechanisms like Context but then for workers have them rely on such "thing".

Anyone has any clue how to check & ask for permissions from a Worker?

For example, in the code labs I've implemented this worker that creates notifications, however, calling NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, builder.build()) will trigger an error telling the developer to implement the permission check.


Solution

  • The only thing you should be doing in your worker is checking if you have permission to show a notification. Requesting a permission should be exclusively for Activities so that you can respond correctly to the user. A user would not want some random permission request showing up when an app is not even showing.