Search code examples
maui

How can NotificationListenerService used in MAUI?


I'm trying to listen to notifications of other apps and for that purpose I tried to utilize NotificationListenerService.

I have seen several examples from Xamarin, but nothing seems to work.

So how is it done in MAUI? How is the NotificationListenerService accessed?

Here is my code from the AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application android:allowBackup="true" android:icon="@mipmap/appicon" android:supportsRtl="true"></application>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" />

    <service android:name=".NotificationListener"
    android:label="@string/NotificationListener"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
        <intent-filter>
            <action android:name="android.service.notification.NotificationListenerService" />
        </intent-filter>
    </service>
</manifest>

And here you can see the file with the class that extends NotificationListenerService:

   using Android.Runtime;
   using Android.OS;
   using Android.Service.Notification;

    [Android.Runtime.Register("android/service/notification/NotificationListenerService", DoNotGenerateAcw = true)]
    public class NLService : NotificationListenerService
        {
            public override void OnCreate()
            {
                base.OnCreate();
                Log.Info("start running", "Service Created");
            }
            public override void OnDestroy()
            {
                base.OnDestroy();
            }
            public override IBinder OnBind(Intent intent)
            {
                return base.OnBind(intent);
            }
            public override bool OnUnbind(Intent intent)
            {
                return base.OnUnbind(intent);
            }
            public override void OnNotificationPosted(StatusBarNotification sbn)
            {
                base.OnNotificationPosted(sbn);
            }
    
            public override void OnNotificationRemoved(StatusBarNotification sbn)
            {
                base.OnNotificationRemoved(sbn);
            }
        }

Solution

  • Well, the solution was to wrap the code in a preprocessor directive:

    #if ANDROID
    
    #endif