프로그래밍/.NET

MAUI, Notification으로 카톡 알림 가져오기

MAJG 2024. 7. 13. 23:50
반응형

결과화면

 

NotificationService.cs

안드로이드 플랫폼에서 동작할 서비스이기 때문에 Platforms/Android 경로에 서비스 파일을 두어야 한다.

using Android.App;
using Android.OS;
using Android.Service.Notification;
using Android.Content;

namespace MauiApp1.Platforms.Android {
    [Service(Exported = true, Label = "NotiService", Permission = "android.permission.BIND_NOTIFICATION_LISTENER_SERVICE")]
    [IntentFilter(new []{ "android.service.notification.NotificationListenerService"})]
    internal class NotificationService:NotificationListenerService {
        public override void OnNotificationPosted(StatusBarNotification? sbn) {
            base.OnNotificationPosted(sbn);

            if (sbn == null) return;

            var packageName = sbn.PackageName;
            if (!string.IsNullOrEmpty(packageName) && packageName == "com.kakao.talk") {
                var notification = sbn.Notification;
                Bundle extras = notification.Extras;

                if (extras != null) {
                    // Get the title from notification  
                    string title = extras.GetString(Notification.ExtraTitle);

                    // Get the content from notification  
                    string content = extras.GetString(Notification.ExtraText);

                    string room = extras.GetString(Notification.ExtraSubText);


                    System.Diagnostics.Debug.WriteLine($"Title : {title}\nMessage : {content}\nRoom : {room}");
                }
            }
        }
    }
}

MainActivity.cs

Notification은 사용자의 개인정보에 접근하기 때문에 권한요청을 해야한다.
안드로이드 앱이 실행될 때 앱에서 알림에 접근할 수 있도록 권한을 요청한다.

    public class MainActivity : MauiAppCompatActivity {
        protected override void OnCreate(Bundle? savedInstanceState) {
            base.OnCreate(savedInstanceState);

            // Notification 권한이 없다면 권한부여 액티비티를 실행
            if(!isNotiPermissionAllowed()) StartActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
        }

        // Notification 권한을 가진 패키지들 중에서 이 앱이 있는지 확인하는 함수
        private bool isNotiPermissionAllowed() => NotificationManagerCompat.GetEnabledListenerPackages(this).Any(enabledPackageName => enabledPackageName == PackageName);
    }

MauiProgram.cs

안드로이드 플랫폼에서 실행되었을 경우에만 NotificationService를 등록하기위해 ANDROID 전처리기를 사용한다.

#if ANDROID
            builder.Services.AddSingleton(new Platforms.Android.NotificationService());
#endif
반응형