How can I request permission for push notifications in my app on Android version 13

Kim Strasser 1,321 Reputation points
2023-02-16T13:06:41.5766667+00:00

I have added the push notifications permission to my AndroidManifest.xml:

https://developer.android.com/develop/ui/views/notifications/notification-permission

<manifest ...
<uses-sdk android:minSdkVersion="30" android:targetSdkVersion="33" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<application ... </application>
</manifest>

But the problem is that no allow/don't alow dialog is displayed when I start my application on my Samsung tablet. I need to open my App info and turn on Notifications myself. After that the notifications are displayed in foreground and background mode.

I want to ask the user automatically for push notification permission when he starts my application but I don't know how to do this. How can I display the allow/don't allow dialog when the user starts my application? Can I do this in OnCreate?

Activity1.cs:

protected override void OnCreate(Bundle bundle)
{
    AndroidX.Core.SplashScreen.SplashScreen.InstallSplashScreen(this);
    base.SetTheme(Resource.Style.MainTheme);
    base.OnCreate(bundle);
    Microsoft.Maui.ApplicationModel.Platform.Init(this, bundle);
    // ...
    IsPlayServicesAvailable();
    CreateNotificationChannel();
    // ...
}

void CreateNotificationChannel()
{
            var channel = new NotificationChannel(CHANNEL_ID,
                                                  "FCM Notifications",
                                                  NotificationImportance.High)
            {

                Description = "Firebase Cloud Messages appear in this channel"
            };
            channel.EnableVibration(true);
            channel.EnableLights(true);
            channel.LightColor = Android.Graphics.Color.Red;
            channel.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification), new AudioAttributes.Builder().SetUsage(AudioUsageKind.Notification).Build());
            channel.LockscreenVisibility = NotificationVisibility.Public;

            var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
            notificationManager.CreateNotificationChannel(channel);
}

public bool IsPlayServicesAvailable()
{
    int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.Success)
    {
        if (GoogleApiAvailability.Instance.IsUserResolvableError(resultCode))
            Texttest = GoogleApiAvailability.Instance.GetErrorString(resultCode);
        else
        {
            Texttest = "This device is not supported";
            Finish();
        }
        return false;
    }
    else
    {
        Texttest = "Google Play Services is available.";
        return true;
    }
}
Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,377 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,341 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 81,016 Reputation points Microsoft External Staff
    2023-02-17T06:09:50.89+00:00

    Hello,

    You can use ActivityCompat.RequestPermissions(this, reqestPermission, REQUEST_P0STNOTIFICATIONS); to request permission.

    Before you request the permission, you need to check the current running version(android 13 or later) and check the permission if it is grand.

    So, I add following code in OnCreate method to check the verion and check the permission for testing

    protected override void OnCreate(Bundle savedInstanceState)
            {
              
               
                SetContentView(R
                CreateNotificationChannel();
                if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu)
                {
                    if (!(CheckPermissionGranted(Manifest.Permission.PostNotifications)))
                    {
                        RequestPostNotificationsPermission();
                    }
                 }
            }
    

    Here is my code about CheckPermissionGranted method to check the permission.

     public bool CheckPermissionGranted(string Permissions)
            {
                // Check if the permission is already available.
                if (ActivityCompat.CheckSelfPermission(this, Permissions) != Permission.Granted)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
    

    If you do not have this permission, you need to request it.

      public static int REQUEST_P0STNOTIFICATIONS = 10023;
            string[] reqestPermission={ "android.permission.POST_NOTIFICATIONS" };
            private void RequestPostNotificationsPermission()
            { 
                          if (ActivityCompat.ShouldShowRequestPermissionRationale(this, "android.permission.POST_NOTIFICATIONS");)
                {
                    // Provide an additional rationale to the user if the permission was not granted
                    // and the user would benefit from additional context for the use of the permission.
                    // For example if the user has previously denied the permission.
                    ActivityCompat.RequestPermissions(this, reqestPermission, REQUEST_P0STNOTIFICATIONS);
                }
                else
                {
                    //P0STNOTIFICATIONS permission has not been granted yet. Request it directly.
                    ActivityCompat.RequestPermissions(this, reqestPermission, REQUEST_P0STNOTIFICATIONS);
                }
            }
    

    If User accept or reject this permission this method will get called:

            public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
            {
                Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
                base.OnRequestPermissionsResult(requestCode, permissions, grantResults);            if (requestCode == REQUEST_P0STNOTIFICATIONS)
                {
                    if (grantResults.Length <= 0)
                    {
                        // If user interaction was interrupted, the permission request is cancelled and you 
                       // receive empty arrays.
                        Log.Info("error", "User interaction was cancelled.");
                    }
                    else if (grantResults[0] == PermissionChecker.PermissionGranted)
                    {
                        // Permission was granted.
                     }
                    else
                    {
                        // Permission denied.
                        Toast.MakeText(this, " REQUEST_P0STNOTIFICATIONS Permission Denied", ToastLength.Long).Show();
                    }
                } 
    }
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Graham McKechnie 441 Reputation points
    2023-02-17T08:09:29.56+00:00

    Did you read the Best Practices section of those docs. As it suggests let the user get used to the app before you ask for the PostNotification permission.

    Have separate methods for CreateNotificationChannel and CreateNotification and let CreateNotificationChanel call CreateNotification.

    Inside CreateNotificationChannel have a test just for (OperatingSystem.IsAndroidVersionAtLeast(33)) for the permission not granted and just return.

    When it it is granted, call the rest of the code in CreateNotificationChannel, with a further test for IsAndroidVersionAtLeast(33) & notificationManager.AreNotificationsEnabled()

    Finding the right place to prompt the user for the permission is the tricky bit. In my own case I display a permanent notification while the app is running, because I'm running a bound service which is started way before any screen appears so there is no right place. So I suggest in help/info section for Android 13, that they turn the permission on manually like I suggested in my earlier answer. Whether the notification is there or not doesn't affect how the app runs, but I've been showing the icon in the in the status and the permant message in the notification since Android 8 and didn't want remove something that users are used to and expect to see. Google should have put a little more thought into how they implemented this.

    Looks like you've got the Android SplashScreen working properly. Thats the first time I've seen a Maui android app do it correctly.

    0 comments No comments

  2. Graham McKechnie 441 Reputation points
    2023-02-17T22:29:33.1966667+00:00

    I don't think there are any restrictions on just creating a notification channel. For instance, anything under Oreo in my case is creating the channel, but it never calls notificationManager.Notify(NOTIFICATION_ID, notification).

    And for Android 13 you are also checking for notificationManager.AreNotificationsEnabled() along with ...AtLeast(33) before you call notificationManager.Notify().

    You could try using ADB (see the doc examples) on all your scenarios.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.