-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
FlutterLocalNotificationsPlugin.java
1973 lines (1807 loc) · 81.3 KB
/
FlutterLocalNotificationsPlugin.java
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.dexterous.flutterlocalnotifications;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationChannelGroup;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioAttributes;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.service.notification.StatusBarNotification;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.app.AlarmManagerCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationCompat.Action.Builder;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.app.Person;
import androidx.core.app.RemoteInput;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.IconCompat;
import com.dexterous.flutterlocalnotifications.isolate.IsolatePreferences;
import com.dexterous.flutterlocalnotifications.models.BitmapSource;
import com.dexterous.flutterlocalnotifications.models.DateTimeComponents;
import com.dexterous.flutterlocalnotifications.models.IconSource;
import com.dexterous.flutterlocalnotifications.models.MessageDetails;
import com.dexterous.flutterlocalnotifications.models.NotificationAction;
import com.dexterous.flutterlocalnotifications.models.NotificationAction.NotificationActionInput;
import com.dexterous.flutterlocalnotifications.models.NotificationChannelAction;
import com.dexterous.flutterlocalnotifications.models.NotificationChannelDetails;
import com.dexterous.flutterlocalnotifications.models.NotificationChannelGroupDetails;
import com.dexterous.flutterlocalnotifications.models.NotificationDetails;
import com.dexterous.flutterlocalnotifications.models.PersonDetails;
import com.dexterous.flutterlocalnotifications.models.ScheduledNotificationRepeatFrequency;
import com.dexterous.flutterlocalnotifications.models.SoundSource;
import com.dexterous.flutterlocalnotifications.models.styles.BigPictureStyleInformation;
import com.dexterous.flutterlocalnotifications.models.styles.BigTextStyleInformation;
import com.dexterous.flutterlocalnotifications.models.styles.DefaultStyleInformation;
import com.dexterous.flutterlocalnotifications.models.styles.InboxStyleInformation;
import com.dexterous.flutterlocalnotifications.models.styles.MessagingStyleInformation;
import com.dexterous.flutterlocalnotifications.models.styles.StyleInformation;
import com.dexterous.flutterlocalnotifications.utils.BooleanUtils;
import com.dexterous.flutterlocalnotifications.utils.LongUtils;
import com.dexterous.flutterlocalnotifications.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import io.flutter.FlutterInjector;
import io.flutter.embedding.engine.loader.FlutterLoader;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;
interface PermissionRequestListener {
void complete(boolean granted);
void fail(String message);
}
/** FlutterLocalNotificationsPlugin */
@Keep
public class FlutterLocalNotificationsPlugin
implements MethodCallHandler,
PluginRegistry.NewIntentListener,
PluginRegistry.RequestPermissionsResultListener,
FlutterPlugin,
ActivityAware {
static final String PAYLOAD = "payload";
static final String NOTIFICATION_ID = "notificationId";
static final String CANCEL_NOTIFICATION = "cancelNotification";
private static final String SHARED_PREFERENCES_KEY = "notification_plugin_cache";
private static final String DISPATCHER_HANDLE = "dispatcher_handle";
private static final String CALLBACK_HANDLE = "callback_handle";
private static final String DRAWABLE = "drawable";
private static final String DEFAULT_ICON = "defaultIcon";
private static final String SELECT_NOTIFICATION = "SELECT_NOTIFICATION";
private static final String SELECT_FOREGROUND_NOTIFICATION_ACTION =
"SELECT_FOREGROUND_NOTIFICATION";
private static final String SCHEDULED_NOTIFICATIONS = "scheduled_notifications";
private static final String INITIALIZE_METHOD = "initialize";
private static final String GET_CALLBACK_HANDLE_METHOD = "getCallbackHandle";
private static final String ARE_NOTIFICATIONS_ENABLED_METHOD = "areNotificationsEnabled";
private static final String CREATE_NOTIFICATION_CHANNEL_GROUP_METHOD =
"createNotificationChannelGroup";
private static final String DELETE_NOTIFICATION_CHANNEL_GROUP_METHOD =
"deleteNotificationChannelGroup";
private static final String CREATE_NOTIFICATION_CHANNEL_METHOD = "createNotificationChannel";
private static final String DELETE_NOTIFICATION_CHANNEL_METHOD = "deleteNotificationChannel";
private static final String GET_ACTIVE_NOTIFICATION_MESSAGING_STYLE_METHOD =
"getActiveNotificationMessagingStyle";
private static final String GET_NOTIFICATION_CHANNELS_METHOD = "getNotificationChannels";
private static final String START_FOREGROUND_SERVICE = "startForegroundService";
private static final String STOP_FOREGROUND_SERVICE = "stopForegroundService";
private static final String PENDING_NOTIFICATION_REQUESTS_METHOD = "pendingNotificationRequests";
private static final String GET_ACTIVE_NOTIFICATIONS_METHOD = "getActiveNotifications";
private static final String SHOW_METHOD = "show";
private static final String CANCEL_METHOD = "cancel";
private static final String CANCEL_ALL_METHOD = "cancelAll";
private static final String SCHEDULE_METHOD = "schedule";
private static final String ZONED_SCHEDULE_METHOD = "zonedSchedule";
private static final String PERIODICALLY_SHOW_METHOD = "periodicallyShow";
private static final String SHOW_DAILY_AT_TIME_METHOD = "showDailyAtTime";
private static final String SHOW_WEEKLY_AT_DAY_AND_TIME_METHOD = "showWeeklyAtDayAndTime";
private static final String GET_NOTIFICATION_APP_LAUNCH_DETAILS_METHOD =
"getNotificationAppLaunchDetails";
private static final String REQUEST_PERMISSION_METHOD = "requestPermission";
private static final String METHOD_CHANNEL = "dexterous.com/flutter/local_notifications";
private static final String INVALID_ICON_ERROR_CODE = "invalid_icon";
private static final String INVALID_LARGE_ICON_ERROR_CODE = "invalid_large_icon";
private static final String INVALID_BIG_PICTURE_ERROR_CODE = "invalid_big_picture";
private static final String INVALID_SOUND_ERROR_CODE = "invalid_sound";
private static final String INVALID_LED_DETAILS_ERROR_CODE = "invalid_led_details";
private static final String UNSUPPORTED_OS_VERSION_ERROR_CODE = "unsupported_os_version";
private static final String GET_ACTIVE_NOTIFICATIONS_ERROR_MESSAGE =
"Android version must be 6.0 or newer to use getActiveNotifications";
private static final String GET_NOTIFICATION_CHANNELS_ERROR_CODE = "getNotificationChannelsError";
private static final String GET_ACTIVE_NOTIFICATION_MESSAGING_STYLE_ERROR_CODE =
"getActiveNotificationMessagingStyleError";
private static final String INVALID_LED_DETAILS_ERROR_MESSAGE =
"Must specify both ledOnMs and ledOffMs to configure the blink cycle on older versions of"
+ " Android before Oreo";
private static final String NOTIFICATION_LAUNCHED_APP = "notificationLaunchedApp";
private static final String INVALID_DRAWABLE_RESOURCE_ERROR_MESSAGE =
"The resource %s could not be found. Please make sure it has been added as a drawable"
+ " resource to your Android head project.";
private static final String INVALID_RAW_RESOURCE_ERROR_MESSAGE =
"The resource %s could not be found. Please make sure it has been added as a raw resource to"
+ " your Android head project.";
private static final String PERMISSION_REQUEST_IN_PROGRESS_ERROR_CODE =
"permissionRequestInProgress";
private static final String PERMISSION_REQUEST_IN_PROGRESS_ERROR_MESSAGE =
"Another permission request is already in progress";
private static final String CANCEL_ID = "id";
private static final String CANCEL_TAG = "tag";
private static final String ACTION_ID = "actionId";
private static final String INPUT_RESULT = "FlutterLocalNotificationsPluginInputResult";
private static final String INPUT = "input";
private static final String NOTIFICATION_RESPONSE_TYPE = "notificationResponseType";
static String NOTIFICATION_DETAILS = "notificationDetails";
static Gson gson;
private MethodChannel channel;
private Context applicationContext;
private Activity mainActivity;
static final int NOTIFICATION_PERMISSION_REQUEST_CODE = 1;
private PermissionRequestListener callback;
private boolean permissionRequestInProgress = false;
static void rescheduleNotifications(Context context) {
ArrayList<NotificationDetails> scheduledNotifications = loadScheduledNotifications(context);
for (NotificationDetails scheduledNotification : scheduledNotifications) {
if (scheduledNotification.repeatInterval == null) {
if (scheduledNotification.timeZoneName == null) {
scheduleNotification(context, scheduledNotification, false);
} else {
zonedScheduleNotification(context, scheduledNotification, false);
}
} else {
repeatNotification(context, scheduledNotification, false);
}
}
}
protected static Notification createNotification(
Context context, NotificationDetails notificationDetails) {
NotificationChannelDetails notificationChannelDetails =
NotificationChannelDetails.fromNotificationDetails(notificationDetails);
if (canCreateNotificationChannel(context, notificationChannelDetails)) {
setupNotificationChannel(context, notificationChannelDetails);
}
Intent intent = getLaunchIntent(context);
intent.setAction(SELECT_NOTIFICATION);
intent.putExtra(NOTIFICATION_ID, notificationDetails.id);
intent.putExtra(PAYLOAD, notificationDetails.payload);
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (VERSION.SDK_INT >= VERSION_CODES.M) {
flags |= PendingIntent.FLAG_IMMUTABLE;
}
PendingIntent pendingIntent =
PendingIntent.getActivity(context, notificationDetails.id, intent, flags);
DefaultStyleInformation defaultStyleInformation =
(DefaultStyleInformation) notificationDetails.styleInformation;
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context, notificationDetails.channelId)
.setContentTitle(
defaultStyleInformation.htmlFormatTitle
? fromHtml(notificationDetails.title)
: notificationDetails.title)
.setContentText(
defaultStyleInformation.htmlFormatBody
? fromHtml(notificationDetails.body)
: notificationDetails.body)
.setTicker(notificationDetails.ticker)
.setAutoCancel(BooleanUtils.getValue(notificationDetails.autoCancel))
.setContentIntent(pendingIntent)
.setPriority(notificationDetails.priority)
.setOngoing(BooleanUtils.getValue(notificationDetails.ongoing))
.setOnlyAlertOnce(BooleanUtils.getValue(notificationDetails.onlyAlertOnce));
if (notificationDetails.actions != null) {
// Space out request codes by 16 so even with 16 actions they won't clash
int requestCode = notificationDetails.id * 16;
for (NotificationAction action : notificationDetails.actions) {
IconCompat icon = null;
if (!TextUtils.isEmpty(action.icon) && action.iconSource != null) {
icon = getIconFromSource(context, action.icon, action.iconSource);
}
Intent actionIntent;
if (action.showsUserInterface != null && action.showsUserInterface) {
actionIntent = getLaunchIntent(context);
actionIntent.setAction(SELECT_FOREGROUND_NOTIFICATION_ACTION);
} else {
actionIntent = new Intent(context, ActionBroadcastReceiver.class);
actionIntent.setAction(ActionBroadcastReceiver.ACTION_TAPPED);
}
actionIntent
.putExtra(NOTIFICATION_ID, notificationDetails.id)
.putExtra(ACTION_ID, action.id)
.putExtra(CANCEL_NOTIFICATION, action.cancelNotification)
.putExtra(PAYLOAD, notificationDetails.payload);
int actionFlags = PendingIntent.FLAG_UPDATE_CURRENT;
if (action.actionInputs == null || action.actionInputs.isEmpty()) {
if (VERSION.SDK_INT >= VERSION_CODES.M) {
actionFlags |= PendingIntent.FLAG_IMMUTABLE;
}
} else {
if (VERSION.SDK_INT >= VERSION_CODES.S) {
actionFlags |= PendingIntent.FLAG_MUTABLE;
}
}
@SuppressLint("UnspecifiedImmutableFlag")
final PendingIntent actionPendingIntent =
action.showsUserInterface != null && action.showsUserInterface
? PendingIntent.getActivity(context, requestCode++, actionIntent, actionFlags)
: PendingIntent.getBroadcast(context, requestCode++, actionIntent, actionFlags);
final Spannable actionTitleSpannable = new SpannableString(action.title);
if (action.titleColor != null) {
actionTitleSpannable.setSpan(
new ForegroundColorSpan(action.titleColor), 0, actionTitleSpannable.length(), 0);
}
Builder actionBuilder = new Builder(icon, actionTitleSpannable, actionPendingIntent);
if (action.contextual != null) {
actionBuilder.setContextual(action.contextual);
}
if (action.showsUserInterface != null) {
actionBuilder.setShowsUserInterface(action.showsUserInterface);
}
if (action.allowGeneratedReplies != null) {
actionBuilder.setAllowGeneratedReplies(action.allowGeneratedReplies);
}
if (action.actionInputs != null) {
for (NotificationActionInput input : action.actionInputs) {
RemoteInput.Builder remoteInput =
new RemoteInput.Builder(INPUT_RESULT).setLabel(input.label);
if (input.allowFreeFormInput != null) {
remoteInput.setAllowFreeFormInput(input.allowFreeFormInput);
}
if (input.allowedMimeTypes != null) {
for (String mimeType : input.allowedMimeTypes) {
remoteInput.setAllowDataType(mimeType, true);
}
}
if (input.choices != null) {
remoteInput.setChoices(input.choices.toArray(new CharSequence[] {}));
}
actionBuilder.addRemoteInput(remoteInput.build());
}
}
builder.addAction(actionBuilder.build());
}
}
setSmallIcon(context, notificationDetails, builder);
builder.setLargeIcon(
getBitmapFromSource(
context, notificationDetails.largeIcon, notificationDetails.largeIconBitmapSource));
if (notificationDetails.color != null) {
builder.setColor(notificationDetails.color.intValue());
}
if (notificationDetails.colorized != null) {
builder.setColorized(notificationDetails.colorized);
}
if (notificationDetails.showWhen != null) {
builder.setShowWhen(BooleanUtils.getValue(notificationDetails.showWhen));
}
if (notificationDetails.when != null) {
builder.setWhen(notificationDetails.when);
}
if (notificationDetails.usesChronometer != null) {
builder.setUsesChronometer(notificationDetails.usesChronometer);
}
if (notificationDetails.chronometerCountDown != null) {
if (VERSION.SDK_INT >= VERSION_CODES.N) {
builder.setChronometerCountDown(notificationDetails.chronometerCountDown);
}
}
if (BooleanUtils.getValue(notificationDetails.fullScreenIntent)) {
builder.setFullScreenIntent(pendingIntent, true);
}
if (!StringUtils.isNullOrEmpty(notificationDetails.shortcutId)) {
builder.setShortcutId(notificationDetails.shortcutId);
}
if (!StringUtils.isNullOrEmpty(notificationDetails.subText)) {
builder.setSubText(notificationDetails.subText);
}
if (notificationDetails.number != null) {
builder.setNumber(notificationDetails.number);
}
setVisibility(notificationDetails, builder);
applyGrouping(notificationDetails, builder);
setSound(context, notificationDetails, builder);
setVibrationPattern(notificationDetails, builder);
setLights(notificationDetails, builder);
setStyle(context, notificationDetails, builder);
setProgress(notificationDetails, builder);
setCategory(notificationDetails, builder);
setTimeoutAfter(notificationDetails, builder);
Notification notification = builder.build();
if (notificationDetails.additionalFlags != null
&& notificationDetails.additionalFlags.length > 0) {
for (int additionalFlag : notificationDetails.additionalFlags) {
notification.flags |= additionalFlag;
}
}
return notification;
}
private static Boolean canCreateNotificationChannel(
Context context, NotificationChannelDetails notificationChannelDetails) {
if (VERSION.SDK_INT >= VERSION_CODES.O) {
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel =
notificationManager.getNotificationChannel(notificationChannelDetails.id);
// only create/update the channel when needed/specified. Allow this happen to when
// channelAction may be null to support cases where notifications had been
// created on older versions of the plugin where channel management options weren't available
// back then
return ((notificationChannel == null
&& (notificationChannelDetails.channelAction == null
|| notificationChannelDetails.channelAction
== NotificationChannelAction.CreateIfNotExists))
|| (notificationChannel != null
&& notificationChannelDetails.channelAction == NotificationChannelAction.Update));
}
return false;
}
private static void setSmallIcon(
Context context,
NotificationDetails notificationDetails,
NotificationCompat.Builder builder) {
if (!StringUtils.isNullOrEmpty(notificationDetails.icon)) {
builder.setSmallIcon(getDrawableResourceId(context, notificationDetails.icon));
} else {
SharedPreferences sharedPreferences =
context.getSharedPreferences(SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
String defaultIcon = sharedPreferences.getString(DEFAULT_ICON, null);
if (StringUtils.isNullOrEmpty(defaultIcon)) {
// for backwards compatibility: this is for handling the old way references to the icon used
// to be kept but should be removed in future
builder.setSmallIcon(notificationDetails.iconResourceId);
} else {
builder.setSmallIcon(getDrawableResourceId(context, defaultIcon));
}
}
}
@NonNull
static Gson buildGson() {
if (gson == null) {
RuntimeTypeAdapterFactory<StyleInformation> styleInformationAdapter =
RuntimeTypeAdapterFactory.of(StyleInformation.class)
.registerSubtype(DefaultStyleInformation.class)
.registerSubtype(BigTextStyleInformation.class)
.registerSubtype(BigPictureStyleInformation.class)
.registerSubtype(InboxStyleInformation.class)
.registerSubtype(MessagingStyleInformation.class);
GsonBuilder builder = new GsonBuilder().registerTypeAdapterFactory(styleInformationAdapter);
gson = builder.create();
}
return gson;
}
private static ArrayList<NotificationDetails> loadScheduledNotifications(Context context) {
ArrayList<NotificationDetails> scheduledNotifications = new ArrayList<>();
SharedPreferences sharedPreferences =
context.getSharedPreferences(SCHEDULED_NOTIFICATIONS, Context.MODE_PRIVATE);
String json = sharedPreferences.getString(SCHEDULED_NOTIFICATIONS, null);
if (json != null) {
Gson gson = buildGson();
Type type = new TypeToken<ArrayList<NotificationDetails>>() {}.getType();
scheduledNotifications = gson.fromJson(json, type);
}
return scheduledNotifications;
}
private static void saveScheduledNotifications(
Context context, ArrayList<NotificationDetails> scheduledNotifications) {
Gson gson = buildGson();
String json = gson.toJson(scheduledNotifications);
SharedPreferences sharedPreferences =
context.getSharedPreferences(SCHEDULED_NOTIFICATIONS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(SCHEDULED_NOTIFICATIONS, json).apply();
}
static void removeNotificationFromCache(Context context, Integer notificationId) {
ArrayList<NotificationDetails> scheduledNotifications = loadScheduledNotifications(context);
for (Iterator<NotificationDetails> it = scheduledNotifications.iterator(); it.hasNext(); ) {
NotificationDetails notificationDetails = it.next();
if (notificationDetails.id.equals(notificationId)) {
it.remove();
break;
}
}
saveScheduledNotifications(context, scheduledNotifications);
}
@SuppressWarnings("deprecation")
private static Spanned fromHtml(String html) {
if (html == null) {
return null;
}
if (VERSION.SDK_INT >= VERSION_CODES.N) {
return Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
} else {
return Html.fromHtml(html);
}
}
private static void scheduleNotification(
Context context,
final NotificationDetails notificationDetails,
Boolean updateScheduledNotificationsCache) {
Gson gson = buildGson();
String notificationDetailsJson = gson.toJson(notificationDetails);
Intent notificationIntent = new Intent(context, ScheduledNotificationReceiver.class);
notificationIntent.putExtra(NOTIFICATION_DETAILS, notificationDetailsJson);
PendingIntent pendingIntent =
getBroadcastPendingIntent(context, notificationDetails.id, notificationIntent);
AlarmManager alarmManager = getAlarmManager(context);
if (BooleanUtils.getValue(notificationDetails.allowWhileIdle)) {
AlarmManagerCompat.setExactAndAllowWhileIdle(
alarmManager,
AlarmManager.RTC_WAKEUP,
notificationDetails.millisecondsSinceEpoch,
pendingIntent);
} else {
AlarmManagerCompat.setExact(
alarmManager,
AlarmManager.RTC_WAKEUP,
notificationDetails.millisecondsSinceEpoch,
pendingIntent);
}
if (updateScheduledNotificationsCache) {
saveScheduledNotification(context, notificationDetails);
}
}
private static void zonedScheduleNotification(
Context context,
final NotificationDetails notificationDetails,
Boolean updateScheduledNotificationsCache) {
Gson gson = buildGson();
String notificationDetailsJson = gson.toJson(notificationDetails);
Intent notificationIntent = new Intent(context, ScheduledNotificationReceiver.class);
notificationIntent.putExtra(NOTIFICATION_DETAILS, notificationDetailsJson);
PendingIntent pendingIntent =
getBroadcastPendingIntent(context, notificationDetails.id, notificationIntent);
AlarmManager alarmManager = getAlarmManager(context);
long epochMilli =
ZonedDateTime.of(
LocalDateTime.parse(notificationDetails.scheduledDateTime),
ZoneId.of(notificationDetails.timeZoneName))
.toInstant()
.toEpochMilli();
if (BooleanUtils.getValue(notificationDetails.allowWhileIdle)) {
AlarmManagerCompat.setExactAndAllowWhileIdle(
alarmManager, AlarmManager.RTC_WAKEUP, epochMilli, pendingIntent);
} else {
AlarmManagerCompat.setExact(alarmManager, AlarmManager.RTC_WAKEUP, epochMilli, pendingIntent);
}
if (updateScheduledNotificationsCache) {
saveScheduledNotification(context, notificationDetails);
}
}
static void scheduleNextRepeatingNotification(
Context context, NotificationDetails notificationDetails) {
long repeatInterval = calculateRepeatIntervalMilliseconds(notificationDetails);
long notificationTriggerTime =
calculateNextNotificationTrigger(notificationDetails.calledAt, repeatInterval);
Gson gson = buildGson();
String notificationDetailsJson = gson.toJson(notificationDetails);
Intent notificationIntent = new Intent(context, ScheduledNotificationReceiver.class);
notificationIntent.putExtra(NOTIFICATION_DETAILS, notificationDetailsJson);
PendingIntent pendingIntent =
getBroadcastPendingIntent(context, notificationDetails.id, notificationIntent);
AlarmManager alarmManager = getAlarmManager(context);
AlarmManagerCompat.setExactAndAllowWhileIdle(
alarmManager, AlarmManager.RTC_WAKEUP, notificationTriggerTime, pendingIntent);
saveScheduledNotification(context, notificationDetails);
}
static Map<String, Object> extractNotificationResponseMap(Intent intent) {
final int notificationId = intent.getIntExtra(NOTIFICATION_ID, 0);
final Map<String, Object> notificationResponseMap = new HashMap<>();
notificationResponseMap.put(NOTIFICATION_ID, notificationId);
notificationResponseMap.put(ACTION_ID, intent.getStringExtra(ACTION_ID));
notificationResponseMap.put(
FlutterLocalNotificationsPlugin.PAYLOAD,
intent.getStringExtra(FlutterLocalNotificationsPlugin.PAYLOAD));
Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
if (remoteInput != null) {
notificationResponseMap.put(INPUT, remoteInput.getString(INPUT_RESULT));
}
if (SELECT_NOTIFICATION.equals(intent.getAction())) {
notificationResponseMap.put(NOTIFICATION_RESPONSE_TYPE, 0);
}
if (SELECT_FOREGROUND_NOTIFICATION_ACTION.equals(intent.getAction())) {
notificationResponseMap.put(NOTIFICATION_RESPONSE_TYPE, 1);
}
return notificationResponseMap;
}
private static PendingIntent getBroadcastPendingIntent(Context context, int id, Intent intent) {
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (VERSION.SDK_INT >= VERSION_CODES.M) {
flags |= PendingIntent.FLAG_IMMUTABLE;
}
return PendingIntent.getBroadcast(context, id, intent, flags);
}
private static void repeatNotification(
Context context,
NotificationDetails notificationDetails,
Boolean updateScheduledNotificationsCache) {
long repeatInterval = calculateRepeatIntervalMilliseconds(notificationDetails);
long notificationTriggerTime = notificationDetails.calledAt;
if (notificationDetails.repeatTime != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, notificationDetails.repeatTime.hour);
calendar.set(Calendar.MINUTE, notificationDetails.repeatTime.minute);
calendar.set(Calendar.SECOND, notificationDetails.repeatTime.second);
if (notificationDetails.day != null) {
calendar.set(Calendar.DAY_OF_WEEK, notificationDetails.day);
}
notificationTriggerTime = calendar.getTimeInMillis();
}
notificationTriggerTime =
calculateNextNotificationTrigger(notificationTriggerTime, repeatInterval);
Gson gson = buildGson();
String notificationDetailsJson = gson.toJson(notificationDetails);
Intent notificationIntent = new Intent(context, ScheduledNotificationReceiver.class);
notificationIntent.putExtra(NOTIFICATION_DETAILS, notificationDetailsJson);
PendingIntent pendingIntent =
getBroadcastPendingIntent(context, notificationDetails.id, notificationIntent);
AlarmManager alarmManager = getAlarmManager(context);
if (BooleanUtils.getValue(notificationDetails.allowWhileIdle)) {
AlarmManagerCompat.setExactAndAllowWhileIdle(
alarmManager, AlarmManager.RTC_WAKEUP, notificationTriggerTime, pendingIntent);
} else {
alarmManager.setInexactRepeating(
AlarmManager.RTC_WAKEUP, notificationTriggerTime, repeatInterval, pendingIntent);
}
if (updateScheduledNotificationsCache) {
saveScheduledNotification(context, notificationDetails);
}
}
private static long calculateNextNotificationTrigger(
long notificationTriggerTime, long repeatInterval) {
// ensures that time is in the future
long currentTime = System.currentTimeMillis();
while (notificationTriggerTime < currentTime) {
notificationTriggerTime += repeatInterval;
}
return notificationTriggerTime;
}
private static long calculateRepeatIntervalMilliseconds(NotificationDetails notificationDetails) {
long repeatInterval = 0;
switch (notificationDetails.repeatInterval) {
case EveryMinute:
repeatInterval = 60000;
break;
case Hourly:
repeatInterval = 60000 * 60;
break;
case Daily:
repeatInterval = 60000 * 60 * 24;
break;
case Weekly:
repeatInterval = 60000 * 60 * 24 * 7;
break;
default:
break;
}
return repeatInterval;
}
private static void saveScheduledNotification(
Context context, NotificationDetails notificationDetails) {
ArrayList<NotificationDetails> scheduledNotifications = loadScheduledNotifications(context);
ArrayList<NotificationDetails> scheduledNotificationsToSave = new ArrayList<>();
for (NotificationDetails scheduledNotification : scheduledNotifications) {
if (scheduledNotification.id.equals(notificationDetails.id)) {
continue;
}
scheduledNotificationsToSave.add(scheduledNotification);
}
scheduledNotificationsToSave.add(notificationDetails);
saveScheduledNotifications(context, scheduledNotificationsToSave);
}
private static int getDrawableResourceId(Context context, String name) {
return context.getResources().getIdentifier(name, DRAWABLE, context.getPackageName());
}
@SuppressWarnings("unchecked")
private static byte[] castObjectToByteArray(Object data) {
byte[] byteArray;
// if data is deserialized by gson, it is of the wrong type and we have to convert it
if (data instanceof ArrayList) {
List<Double> l = (ArrayList<Double>) data;
byteArray = new byte[l.size()];
for (int i = 0; i < l.size(); i++) {
byteArray[i] = (byte) l.get(i).intValue();
}
} else {
byteArray = (byte[]) data;
}
return byteArray;
}
private static Bitmap getBitmapFromSource(
Context context, Object data, BitmapSource bitmapSource) {
Bitmap bitmap = null;
if (bitmapSource == BitmapSource.DrawableResource) {
bitmap =
BitmapFactory.decodeResource(
context.getResources(), getDrawableResourceId(context, (String) data));
} else if (bitmapSource == BitmapSource.FilePath) {
bitmap = BitmapFactory.decodeFile((String) data);
} else if (bitmapSource == BitmapSource.ByteArray) {
byte[] byteArray = castObjectToByteArray(data);
bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
return bitmap;
}
private static IconCompat getIconFromSource(Context context, Object data, IconSource iconSource) {
IconCompat icon = null;
switch (iconSource) {
case DrawableResource:
icon =
IconCompat.createWithResource(context, getDrawableResourceId(context, (String) data));
break;
case BitmapFilePath:
icon = IconCompat.createWithBitmap(BitmapFactory.decodeFile((String) data));
break;
case ContentUri:
icon = IconCompat.createWithContentUri((String) data);
break;
case FlutterBitmapAsset:
try {
FlutterLoader flutterLoader = FlutterInjector.instance().flutterLoader();
AssetFileDescriptor assetFileDescriptor =
context.getAssets().openFd(flutterLoader.getLookupKeyForAsset((String) data));
FileInputStream fileInputStream = assetFileDescriptor.createInputStream();
icon = IconCompat.createWithBitmap(BitmapFactory.decodeStream(fileInputStream));
fileInputStream.close();
assetFileDescriptor.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
break;
case ByteArray:
byte[] byteArray = castObjectToByteArray(data);
icon = IconCompat.createWithData(byteArray, 0, byteArray.length);
default:
break;
}
return icon;
}
/**
* Sets the visibility property to the input Notification Builder
*
* @throws IllegalArgumentException If `notificationDetails.visibility` is not null but also not
* matches any known index.
*/
private static void setVisibility(
NotificationDetails notificationDetails, NotificationCompat.Builder builder) {
if (notificationDetails.visibility == null) {
return;
}
int visibility;
switch (notificationDetails.visibility) {
case 0: // Private
visibility = NotificationCompat.VISIBILITY_PRIVATE;
break;
case 1: // Public
visibility = NotificationCompat.VISIBILITY_PUBLIC;
break;
case 2: // Secret
visibility = NotificationCompat.VISIBILITY_SECRET;
break;
default:
throw new IllegalArgumentException("Unknown index: " + notificationDetails.visibility);
}
builder.setVisibility(visibility);
}
private static void applyGrouping(
NotificationDetails notificationDetails, NotificationCompat.Builder builder) {
boolean isGrouped = false;
if (!StringUtils.isNullOrEmpty(notificationDetails.groupKey)) {
builder.setGroup(notificationDetails.groupKey);
isGrouped = true;
}
if (isGrouped) {
if (BooleanUtils.getValue(notificationDetails.setAsGroupSummary)) {
builder.setGroupSummary(true);
}
builder.setGroupAlertBehavior(notificationDetails.groupAlertBehavior);
}
}
private static void setVibrationPattern(
NotificationDetails notificationDetails, NotificationCompat.Builder builder) {
if (BooleanUtils.getValue(notificationDetails.enableVibration)) {
if (notificationDetails.vibrationPattern != null
&& notificationDetails.vibrationPattern.length > 0) {
builder.setVibrate(notificationDetails.vibrationPattern);
}
} else {
builder.setVibrate(new long[] {0});
}
}
private static void setLights(
NotificationDetails notificationDetails, NotificationCompat.Builder builder) {
if (BooleanUtils.getValue(notificationDetails.enableLights)
&& notificationDetails.ledOnMs != null
&& notificationDetails.ledOffMs != null) {
builder.setLights(
notificationDetails.ledColor, notificationDetails.ledOnMs, notificationDetails.ledOffMs);
}
}
private static void setSound(
Context context,
NotificationDetails notificationDetails,
NotificationCompat.Builder builder) {
if (BooleanUtils.getValue(notificationDetails.playSound)) {
Uri uri =
retrieveSoundResourceUri(
context, notificationDetails.sound, notificationDetails.soundSource);
builder.setSound(uri);
} else {
builder.setSound(null);
}
}
private static void setCategory(
NotificationDetails notificationDetails, NotificationCompat.Builder builder) {
if (notificationDetails.category == null) {
return;
}
builder.setCategory(notificationDetails.category);
}
private static void setTimeoutAfter(
NotificationDetails notificationDetails, NotificationCompat.Builder builder) {
if (notificationDetails.timeoutAfter == null) {
return;
}
builder.setTimeoutAfter(notificationDetails.timeoutAfter);
}
private static Intent getLaunchIntent(Context context) {
String packageName = context.getPackageName();
PackageManager packageManager = context.getPackageManager();
return packageManager.getLaunchIntentForPackage(packageName);
}
private static void setStyle(
Context context,
NotificationDetails notificationDetails,
NotificationCompat.Builder builder) {
switch (notificationDetails.style) {
case BigPicture:
setBigPictureStyle(context, notificationDetails, builder);
break;
case BigText:
setBigTextStyle(notificationDetails, builder);
break;
case Inbox:
setInboxStyle(notificationDetails, builder);
break;
case Messaging:
setMessagingStyle(context, notificationDetails, builder);
break;
case Media:
setMediaStyle(builder);
break;
default:
break;
}
}
private static void setProgress(
NotificationDetails notificationDetails, NotificationCompat.Builder builder) {
if (BooleanUtils.getValue(notificationDetails.showProgress)) {
builder.setProgress(
notificationDetails.maxProgress,
notificationDetails.progress,
notificationDetails.indeterminate);
}
}
private static void setBigPictureStyle(
Context context,
NotificationDetails notificationDetails,
NotificationCompat.Builder builder) {
BigPictureStyleInformation bigPictureStyleInformation =
(BigPictureStyleInformation) notificationDetails.styleInformation;
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
if (bigPictureStyleInformation.contentTitle != null) {
CharSequence contentTitle =
bigPictureStyleInformation.htmlFormatContentTitle
? fromHtml(bigPictureStyleInformation.contentTitle)
: bigPictureStyleInformation.contentTitle;
bigPictureStyle.setBigContentTitle(contentTitle);
}
if (bigPictureStyleInformation.summaryText != null) {
CharSequence summaryText =
bigPictureStyleInformation.htmlFormatSummaryText
? fromHtml(bigPictureStyleInformation.summaryText)
: bigPictureStyleInformation.summaryText;
bigPictureStyle.setSummaryText(summaryText);
}
if (bigPictureStyleInformation.hideExpandedLargeIcon) {
bigPictureStyle.bigLargeIcon(null);
} else {
if (bigPictureStyleInformation.largeIcon != null) {
bigPictureStyle.bigLargeIcon(
getBitmapFromSource(
context,
bigPictureStyleInformation.largeIcon,
bigPictureStyleInformation.largeIconBitmapSource));
}
}
bigPictureStyle.bigPicture(
getBitmapFromSource(
context,
bigPictureStyleInformation.bigPicture,
bigPictureStyleInformation.bigPictureBitmapSource));
builder.setStyle(bigPictureStyle);
}
private static void setInboxStyle(
NotificationDetails notificationDetails, NotificationCompat.Builder builder) {
InboxStyleInformation inboxStyleInformation =
(InboxStyleInformation) notificationDetails.styleInformation;
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
if (inboxStyleInformation.contentTitle != null) {
CharSequence contentTitle =
inboxStyleInformation.htmlFormatContentTitle
? fromHtml(inboxStyleInformation.contentTitle)
: inboxStyleInformation.contentTitle;
inboxStyle.setBigContentTitle(contentTitle);
}
if (inboxStyleInformation.summaryText != null) {
CharSequence summaryText =
inboxStyleInformation.htmlFormatSummaryText
? fromHtml(inboxStyleInformation.summaryText)
: inboxStyleInformation.summaryText;
inboxStyle.setSummaryText(summaryText);
}
if (inboxStyleInformation.lines != null) {
for (String line : inboxStyleInformation.lines) {
inboxStyle.addLine(inboxStyleInformation.htmlFormatLines ? fromHtml(line) : line);
}
}
builder.setStyle(inboxStyle);
}
private static void setMediaStyle(NotificationCompat.Builder builder) {
androidx.media.app.NotificationCompat.MediaStyle mediaStyle =
new androidx.media.app.NotificationCompat.MediaStyle();
builder.setStyle(mediaStyle);
}
private static void setMessagingStyle(
Context context,
NotificationDetails notificationDetails,
NotificationCompat.Builder builder) {
MessagingStyleInformation messagingStyleInformation =
(MessagingStyleInformation) notificationDetails.styleInformation;
Person person = buildPerson(context, messagingStyleInformation.person);
NotificationCompat.MessagingStyle messagingStyle =
new NotificationCompat.MessagingStyle(person);
messagingStyle.setGroupConversation(
BooleanUtils.getValue(messagingStyleInformation.groupConversation));
if (messagingStyleInformation.conversationTitle != null) {
messagingStyle.setConversationTitle(messagingStyleInformation.conversationTitle);
}
if (messagingStyleInformation.messages != null
&& !messagingStyleInformation.messages.isEmpty()) {
for (MessageDetails messageDetails : messagingStyleInformation.messages) {
NotificationCompat.MessagingStyle.Message message = createMessage(context, messageDetails);
messagingStyle.addMessage(message);