~phroa/phone-app

ref: 61842a204eb6b12febfd101510f130d58e307d5d phone-app/phms/BackgroundService.cs -rw-r--r-- 2.0 KiB
61842a20Jack Stratton Set up a background service for notifications 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using Android.App;
using Android.Content;
using Android.OS;

namespace phms
{
    using R = Resource;
    
    [Service(Enabled = true)]
    public class BackgroundService : Service
    {
        public const string UpdateNotificationAction = "phms.backgroundservice.updatenotification";
        
        private const int NotificationId = 39;
        
        private NotificationChannel? _notificationChannel;
        private Binder? _binder;

        public override IBinder OnBind(Intent? intent)
        {
            return _binder ??= new Binder();
        }

        public override void OnCreate()
        {
            base.OnCreate();
            _notificationChannel ??= new NotificationChannel("phms", "phms", NotificationImportance.High);

            Notify("Service OnCreate");
        }

        public override StartCommandResult OnStartCommand(Intent? intent, StartCommandFlags flags, int startId)
        {
            var ret = base.OnStartCommand(intent, flags, startId);

            if (intent?.Action == UpdateNotificationAction)
            {
                Notify(intent.Extras?.GetString("message") ?? "Something important!");
            }
            
            return ret;
        }

        private void Notify(string message)
        {
            if (!GetNotificationManager().NotificationChannels.Contains(_notificationChannel))
            {
                GetNotificationManager().CreateNotificationChannel(_notificationChannel);
            }
            
            var n = new Notification.Builder(this, _notificationChannel?.Id)
                .SetContentTitle("phms")
                .SetContentText(message)
                .SetSmallIcon(Android.Resource.Drawable.SymDefAppIcon)
                .Build();
 
            GetNotificationManager().Notify(NotificationId, n);
        }

        private NotificationManager GetNotificationManager()
        {
            return (NotificationManager) (GetSystemService(NotificationService) ?? throw new Exception("Couldn't get a notification service"));
        }
    }
}