/
OneSignal.java
3469 lines (2898 loc) · 133 KB
/
OneSignal.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
/**
* Modified MIT License
*
* Copyright 2019 OneSignal
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* 1. The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 2. All copies of substantial portions of the Software may only be used in connection
* with services provided by OneSignal.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.onesignal;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;
import androidx.core.app.NotificationCompat;
import com.onesignal.OneSignalDbContract.NotificationTable;
import com.onesignal.influence.data.OSTrackerFactory;
import com.onesignal.influence.domain.OSInfluence;
import com.onesignal.outcomes.data.OSOutcomeEventsFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.ref.WeakReference;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import static com.onesignal.GenerateNotification.BUNDLE_KEY_ACTION_ID;
import static com.onesignal.GenerateNotification.BUNDLE_KEY_ANDROID_NOTIFICATION_ID;
import static com.onesignal.NotificationBundleProcessor.newJsonArray;
/**
* The main OneSignal class - this is where you will interface with the OneSignal SDK
* <br/><br/>
* <b>Reminder:</b> Add your {@code onesignal_app_id} to your build.gradle config in <i>android</i> > <i>defaultConfig</i>
* <br/>
* @see <a href="https://documentation.onesignal.com/docs/android-sdk-setup#section-1-gradle-setup">OneSignal Gradle Setup</a>
*/
public class OneSignal {
// If the app is this amount time or longer in the background we will count the session as done
static final long MIN_ON_SESSION_TIME_MILLIS = 30 * 1_000L;
public enum LOG_LEVEL {
NONE, FATAL, ERROR, WARN, INFO, DEBUG, VERBOSE
}
/**
* An app entry type enum for knowing how the user foregrounded or backgrounded the app.
* <br/><br/>
* The enum also helps decide the type of session the user is in an is tracked in {@link OneSignal#sessionManager}
* from the {@link OSSessionManager}.
* <br/><br/>
* {@link AppEntryAction#NOTIFICATION_CLICK} will always lead a overridden {@link com.onesignal.influence.domain.OSInfluenceType#DIRECT}.
* {@link AppEntryAction#APP_OPEN} on a new session notifications within the attribution window
* parameter, this will lead to a {@link com.onesignal.influence.domain.OSInfluenceType#DIRECT}.
* <br/><br/>
* @see OneSignal#onAppFocus
* @see OneSignal#onAppLostFocus
* @see OneSignal#handleNotificationOpen
*/
public enum AppEntryAction {
/**
* Entered the app through opening a notification
*/
NOTIFICATION_CLICK,
/**
* Entered the app through clicking the icon
*/
APP_OPEN,
/**
* App came from the background
*/
APP_CLOSE;
public boolean isNotificationClick() {
return this.equals(NOTIFICATION_CLICK);
}
public boolean isAppOpen() {
return this.equals(APP_OPEN);
}
public boolean isAppClose() {
return this.equals(APP_CLOSE);
}
}
/**
* Implement this interface on a class with a default public constructor and provide class with namespace
* as a value to a new `meta-data` tag with the key name of "com.onesignal.NotificationServiceExtension" in
* your AndroidManifest.xml.
* ex. <meta-data android:name="com.onesignal.NotificationServiceExtension" android:value="com.company.MyNotificationExtensionService" />
* <br/><br/>
* Allows for modification of a notification by calling {@link OSNotification#mutableCopy}
* instance and passing it into {@link OSMutableNotification#setExtender(NotificationCompat.Extender)}
* To display the notification, call {@link OSNotificationReceivedEvent#complete(OSNotification)} with a notification instance.
* To omit displaying a notification call {@link OSNotificationReceivedEvent#complete(OSNotification)} with null.
*/
public interface OSRemoteNotificationReceivedHandler {
void remoteNotificationReceived(Context context, OSNotificationReceivedEvent notificationReceivedEvent);
}
/**
* Meant to be implemented with {@link OneSignal#setNotificationWillShowInForegroundHandler(OSNotificationWillShowInForegroundHandler)}
* <br/><br/>
* Call {@link OSNotificationReceivedEvent#complete(OSNotification)} with null
* for not displaying notification or {@link OSMutableNotification} to modify notification before displaying.
* If {@link OSNotificationReceivedEvent#complete(OSNotification)} is not called within 25 seconds, original notification will be displayed.
* <br/><br/>
* TODO: Update docs with new NotificationReceivedHandler
* @see <a href="https://documentation.onesignal.com/docs/android-native-sdk#notificationreceivedhandler">NotificationReceivedHandler | OneSignal Docs</a>
*/
public interface OSNotificationWillShowInForegroundHandler {
void notificationWillShowInForeground(OSNotificationReceivedEvent notificationReceivedEvent);
}
/**
* An interface used to process a OneSignal notification the user just tapped on.
* <br/>
* Set this during OneSignal init in
* {@link OneSignal#setNotificationOpenedHandler(OSNotificationOpenedHandler)}
* <br/><br/>
* @see <a href="https://documentation.onesignal.com/docs/android-native-sdk#notificationopenedhandler">NotificationOpenedHandler | OneSignal Docs</a>
*/
public interface OSNotificationOpenedHandler {
/**
* Fires when a user taps on a notification.
* @param result a {@link OSNotificationOpenedResult} with the user's response and properties of this notification
*/
void notificationOpened(OSNotificationOpenedResult result);
}
/**
* An interface used to process a OneSignal In-App Message the user just tapped on.
* <br/>
* Set this during OneSignal init in
* {@link OneSignal#setInAppMessageClickHandler(OSInAppMessageClickHandler)}
*/
public interface OSInAppMessageClickHandler {
/**
* Fires when a user taps on a clickable element in the notification such as a button or image
* @param result a {@link OSInAppMessageAction}
**/
void inAppMessageClicked(OSInAppMessageAction result);
}
/**
* Interface which you can implement and pass to {@link OneSignal#getTags(OSGetTagsHandler)} to
* get all the tags set on a user
* <br/><br/>
* <b>Note:</b> the {@link #tagsAvailable(JSONObject)} callback does not run on the Main(UI)
* Thread, so be aware when modifying UI in this method.
*/
public interface OSGetTagsHandler {
/**
* <b>Note:</b> this callback does not run on the Main(UI)
* Thread, so be aware when modifying UI in this method.
* @param tags a JSONObject containing the OneSignal tags for the user in a key/value map
*/
void tagsAvailable(JSONObject tags);
}
public interface ChangeTagsUpdateHandler {
void onSuccess(JSONObject tags);
void onFailure(SendTagsError error);
}
public static class SendTagsError {
private String message;
private int code;
SendTagsError(int errorCode, String errorMessage) {
this.message = errorMessage;
this.code = errorCode;
}
public int getCode() { return code; }
public String getMessage() { return message; }
}
public enum ExternalIdErrorType {
REQUIRES_EXTERNAL_ID_AUTH, INVALID_OPERATION, NETWORK
}
public static class ExternalIdError {
private ExternalIdErrorType type;
private String message;
ExternalIdError(ExternalIdErrorType type, String message) {
this.type = type;
this.message = message;
}
public ExternalIdErrorType getType() {
return type;
}
public String getMessage() {
return message;
}
}
public interface OSExternalUserIdUpdateCompletionHandler {
void onSuccess(JSONObject results);
void onFailure(ExternalIdError error);
}
interface OSInternalExternalUserIdUpdateCompletionHandler {
void onComplete(String channel, boolean success);
}
public enum SMSErrorType {
VALIDATION, REQUIRES_SMS_AUTH, INVALID_OPERATION, NETWORK
}
public static class OSSMSUpdateError {
private SMSErrorType type;
private String message;
OSSMSUpdateError(SMSErrorType type, String message) {
this.type = type;
this.message = message;
}
public SMSErrorType getType() {
return type;
}
public String getMessage() {
return message;
}
}
public interface OSSMSUpdateHandler {
void onSuccess(JSONObject result);
void onFailure(OSSMSUpdateError error);
}
private static OSSMSUpdateHandler smsUpdateHandler;
private static OSSMSUpdateHandler smsLogoutHandler;
public enum EmailErrorType {
VALIDATION, REQUIRES_EMAIL_AUTH, INVALID_OPERATION, NETWORK
}
public static class EmailUpdateError {
private EmailErrorType type;
private String message;
EmailUpdateError(EmailErrorType type, String message) {
this.type = type;
this.message = message;
}
public EmailErrorType getType() {
return type;
}
public String getMessage() {
return message;
}
}
public interface EmailUpdateHandler {
void onSuccess();
void onFailure(EmailUpdateError error);
}
private static EmailUpdateHandler emailUpdateHandler;
private static EmailUpdateHandler emailLogoutHandler;
/**
* Fires delegate when the notification was created or fails to be created.
*/
public interface PostNotificationResponseHandler {
void onSuccess(JSONObject response);
void onFailure(JSONObject response);
}
interface EntryStateListener {
// Fire with the last appEntryState that just ended.
void onEntryStateChange(AppEntryAction appEntryState);
}
private static List<EntryStateListener> entryStateListeners = new ArrayList<>();
static void callEntryStateListeners(AppEntryAction appEntryState) {
List<EntryStateListener> entryStateListeners = new ArrayList<>(OneSignal.entryStateListeners);
for (EntryStateListener sessionListener : entryStateListeners) {
sessionListener.onEntryStateChange(appEntryState);
}
}
static void addEntryStateListener(EntryStateListener sessionListener, AppEntryAction appEntryState) {
// We only care for open and close changes
if (!appEntryState.equals(AppEntryAction.NOTIFICATION_CLICK))
entryStateListeners.add(sessionListener);
}
static void removeEntryStateListener(EntryStateListener sessionListener) {
entryStateListeners.remove(sessionListener);
}
static Context appContext;
static WeakReference<Activity> appActivity;
static String appId;
static String googleProjectNumber;
@Nullable
static Activity getCurrentActivity() {
ActivityLifecycleHandler activityLifecycleHandler = ActivityLifecycleListener.getActivityLifecycleHandler();
return activityLifecycleHandler != null ? activityLifecycleHandler.getCurActivity() : null;
}
private static LOG_LEVEL visualLogLevel = LOG_LEVEL.NONE;
private static LOG_LEVEL logCatLevel = LOG_LEVEL.WARN;
private static String userId = null;
private static String emailId = null;
private static String smsId = null;
private static int subscribableStatus = Integer.MAX_VALUE;
static OSRemoteNotificationReceivedHandler remoteNotificationReceivedHandler;
static OSNotificationWillShowInForegroundHandler notificationWillShowInForegroundHandler;
static OSNotificationOpenedHandler notificationOpenedHandler;
static OSInAppMessageClickHandler inAppMessageClickHandler;
// Is the init() of OneSignal SDK finished yet
private static boolean initDone;
static boolean isInitDone() {
return initDone;
}
// Is the app in the inForeground or not
private static boolean inForeground;
static boolean isInForeground() {
return inForeground;
}
static void setInForeground(boolean inForeground) {
OneSignal.inForeground = inForeground;
}
// Tells the action taken to enter the app
@NonNull private static AppEntryAction appEntryState = AppEntryAction.APP_CLOSE;
static @NonNull AppEntryAction getAppEntryState() {
return appEntryState;
}
private static TrackGooglePurchase trackGooglePurchase;
private static TrackAmazonPurchase trackAmazonPurchase;
private static TrackFirebaseAnalytics trackFirebaseAnalytics;
private static final String VERSION = "040200";
public static String getSdkVersionRaw() {
return VERSION;
}
private static OSLogger logger = new OSLogWrapper();
private static FocusTimeController focusTimeController = new FocusTimeController(new OSFocusTimeProcessorFactory(), logger);
private static OSSessionManager.SessionListener sessionListener = new OSSessionManager.SessionListener() {
@Override
public void onSessionEnding(@NonNull List<OSInfluence> lastInfluences) {
if (outcomeEventsController == null)
OneSignal.Log(LOG_LEVEL.WARN, "OneSignal onSessionEnding called before init!");
if (outcomeEventsController != null)
outcomeEventsController.cleanOutcomes();
focusTimeController.onSessionEnded(lastInfluences);
}
};
private static OSInAppMessageControllerFactory inAppMessageControllerFactory = new OSInAppMessageControllerFactory();
static OSInAppMessageController getInAppMessageController() {
return inAppMessageControllerFactory.getController(getDBHelperInstance(), getLogger());
}
private static OSTime time = new OSTimeImpl();
private static OSRemoteParamController remoteParamController = new OSRemoteParamController();
private static OSTaskController taskController = new OSTaskController(remoteParamController, logger);
private static OneSignalAPIClient apiClient = new OneSignalRestClientWrapper();
private static OSSharedPreferences preferences = new OSSharedPreferencesWrapper();
private static OSTrackerFactory trackerFactory = new OSTrackerFactory(preferences, logger, time);
private static OSSessionManager sessionManager = new OSSessionManager(sessionListener, trackerFactory, logger);
@Nullable private static OSOutcomeEventsController outcomeEventsController;
@Nullable private static OSOutcomeEventsFactory outcomeEventsFactory;
@Nullable private static AdvertisingIdentifierProvider adIdProvider;
private static synchronized @Nullable AdvertisingIdentifierProvider getAdIdProvider() {
if (adIdProvider == null) {
if (OSUtils.isAndroidDeviceType())
adIdProvider = new AdvertisingIdProviderGPS();
}
return adIdProvider;
}
@SuppressWarnings("WeakerAccess")
public static String sdkType = "native";
private static String lastRegistrationId;
@NonNull private static OSUtils osUtils = new OSUtils();
private static boolean registerForPushFired, locationFired, getTagsCall, waitingToPostStateSync, androidParamsRequestStarted;
private static LocationController.LocationPoint lastLocationPoint;
private static Collection<JSONArray> unprocessedOpenedNotifs = new ArrayList<>();
private static HashSet<String> postedOpenedNotifIds = new HashSet<>();
private static final ArrayList<OSGetTagsHandler> pendingGetTagsHandlers = new ArrayList<>();
private static DelayedConsentInitializationParameters delayedInitParams;
static DelayedConsentInitializationParameters getDelayedInitParams() {
return delayedInitParams;
}
// Start PermissionState
private static OSPermissionState currentPermissionState;
private static OSPermissionState getCurrentPermissionState(Context context) {
if (context == null)
return null;
if (currentPermissionState == null) {
currentPermissionState = new OSPermissionState(false);
currentPermissionState.getObservable().addObserverStrong(new OSPermissionChangedInternalObserver());
}
return currentPermissionState;
}
static OSPermissionState lastPermissionState;
private static OSPermissionState getLastPermissionState(Context context) {
if (context == null)
return null;
if (lastPermissionState == null)
lastPermissionState = new OSPermissionState(true);
return lastPermissionState;
}
private static OSObservable<OSPermissionObserver, OSPermissionStateChanges> permissionStateChangesObserver;
static OSObservable<OSPermissionObserver, OSPermissionStateChanges> getPermissionStateChangesObserver() {
if (permissionStateChangesObserver == null)
permissionStateChangesObserver = new OSObservable<>("onOSPermissionChanged", true);
return permissionStateChangesObserver;
}
// End PermissionState
// Start SubscriptionState
private static OSSubscriptionState currentSubscriptionState;
private static OSSubscriptionState getCurrentSubscriptionState(Context context) {
if (context == null)
return null;
if (currentSubscriptionState == null) {
currentSubscriptionState = new OSSubscriptionState(false, getCurrentPermissionState(context).areNotificationsEnabled());
getCurrentPermissionState(context).getObservable().addObserver(currentSubscriptionState);
currentSubscriptionState.getObservable().addObserverStrong(new OSSubscriptionChangedInternalObserver());
}
return currentSubscriptionState;
}
static OSSubscriptionState lastSubscriptionState;
private static OSSubscriptionState getLastSubscriptionState(Context context) {
if (context == null)
return null;
if (lastSubscriptionState == null)
lastSubscriptionState = new OSSubscriptionState(true, false);
return lastSubscriptionState;
}
private static OSObservable<OSSubscriptionObserver, OSSubscriptionStateChanges> subscriptionStateChangesObserver;
static OSObservable<OSSubscriptionObserver, OSSubscriptionStateChanges> getSubscriptionStateChangesObserver() {
if (subscriptionStateChangesObserver == null)
subscriptionStateChangesObserver = new OSObservable<>("onOSSubscriptionChanged", true);
return subscriptionStateChangesObserver;
}
// End SubscriptionState
// Start EmailSubscriptionState
private static OSEmailSubscriptionState currentEmailSubscriptionState;
private static OSEmailSubscriptionState getCurrentEmailSubscriptionState(Context context) {
if (context == null)
return null;
if (currentEmailSubscriptionState == null) {
currentEmailSubscriptionState = new OSEmailSubscriptionState(false);
currentEmailSubscriptionState.getObservable().addObserverStrong(new OSEmailSubscriptionChangedInternalObserver());
}
return currentEmailSubscriptionState;
}
static OSEmailSubscriptionState getEmailSubscriptionState() {
return getCurrentEmailSubscriptionState(appContext);
}
static OSEmailSubscriptionState lastEmailSubscriptionState;
private static OSEmailSubscriptionState getLastEmailSubscriptionState(Context context) {
if (context == null)
return null;
if (lastEmailSubscriptionState == null)
lastEmailSubscriptionState = new OSEmailSubscriptionState(true);
return lastEmailSubscriptionState;
}
private static OSObservable<OSEmailSubscriptionObserver, OSEmailSubscriptionStateChanges> emailSubscriptionStateChangesObserver;
static OSObservable<OSEmailSubscriptionObserver, OSEmailSubscriptionStateChanges> getEmailSubscriptionStateChangesObserver() {
if (emailSubscriptionStateChangesObserver == null)
emailSubscriptionStateChangesObserver = new OSObservable<>("onOSEmailSubscriptionChanged", true);
return emailSubscriptionStateChangesObserver;
}
// End EmailSubscriptionState
// Start SMSSubscriptionState
private static OSSMSSubscriptionState currentSMSSubscriptionState;
private static OSSMSSubscriptionState getCurrentSMSSubscriptionState(Context context) {
if (context == null)
return null;
if (currentSMSSubscriptionState == null) {
currentSMSSubscriptionState = new OSSMSSubscriptionState(false);
currentSMSSubscriptionState.getObservable().addObserverStrong(new OSSMSSubscriptionChangedInternalObserver());
}
return currentSMSSubscriptionState;
}
static OSSMSSubscriptionState getSMSSubscriptionState() {
return getCurrentSMSSubscriptionState(appContext);
}
static OSSMSSubscriptionState lastSMSSubscriptionState;
private static OSSMSSubscriptionState getLastSMSSubscriptionState(Context context) {
if (context == null)
return null;
if (lastSMSSubscriptionState == null)
lastSMSSubscriptionState = new OSSMSSubscriptionState(true);
return lastSMSSubscriptionState;
}
private static OSObservable<OSSMSSubscriptionObserver, OSSMSSubscriptionStateChanges> smsSubscriptionStateChangesObserver;
static OSObservable<OSSMSSubscriptionObserver, OSSMSSubscriptionStateChanges> getSMSSubscriptionStateChangesObserver() {
if (smsSubscriptionStateChangesObserver == null)
smsSubscriptionStateChangesObserver = new OSObservable<>("onSMSSubscriptionChanged", true);
return smsSubscriptionStateChangesObserver;
}
// End SMSSubscriptionState
/**
* Get the current user data, notification and permissions state.
*/
@Nullable
public static OSDeviceState getDeviceState() {
if (appContext == null) {
logger.error("OneSignal.initWithContext has not been called. Could not get OSDeviceState");
return null;
}
OSSubscriptionState subscriptionStatus = getCurrentSubscriptionState(appContext);
OSPermissionState permissionStatus = getCurrentPermissionState(appContext);
OSEmailSubscriptionState emailSubscriptionStatus = getCurrentEmailSubscriptionState(appContext);
OSSMSSubscriptionState smsSubscriptionStatus = getCurrentSMSSubscriptionState(appContext);
return new OSDeviceState(subscriptionStatus, permissionStatus, emailSubscriptionStatus, smsSubscriptionStatus);
}
private static class IAPUpdateJob {
JSONArray toReport;
boolean newAsExisting;
OneSignalRestClient.ResponseHandler restResponseHandler;
IAPUpdateJob(JSONArray toReport) {
this.toReport = toReport;
}
}
private static IAPUpdateJob iapUpdateJob;
/**
* If notifications are disabled for your app, unsubscribe the user from OneSignal.
* This will happen when your users go to <i>Settings</i> > <i>Apps</i> and turn off notifications or
* they long press your notifications and select "block notifications". This is {@code false} by default.
* @param set if {@code false} - don't unsubscribe users<br/>
* if {@code true} - unsubscribe users when notifications are disabled<br/>
* the default is {@code false}
* @return the builder you called this method on
*/
public static void unsubscribeWhenNotificationsAreDisabled(final boolean set) {
if (taskController.shouldQueueTaskForInit(OSTaskController.UNSUBSCRIBE_WHEN_NOTIFICATION_ARE_DISABLED)) {
logger.error("Waiting for remote params. " +
"Moving " + OSTaskController.UNSUBSCRIBE_WHEN_NOTIFICATION_ARE_DISABLED + " operation to a pending task queue.");
taskController.addTaskToQueue(new Runnable() {
@Override
public void run() {
logger.debug("Running " + OSTaskController.UNSUBSCRIBE_WHEN_NOTIFICATION_ARE_DISABLED + " operation from pending task queue.");
unsubscribeWhenNotificationsAreDisabled(set);
}
});
return;
}
// Already set by remote params
if (getRemoteParamController().hasUnsubscribeNotificationKey()) {
logger.warning("unsubscribeWhenNotificationsAreDisabled already called by remote params!, ignoring user set");
return;
}
getRemoteParamController().saveUnsubscribeWhenNotificationsAreDisabled(set);
}
/**
* 1/2 steps in OneSignal init, relying on initWithContext (usage order does not matter)
* Sets the app id OneSignal should use in the application
* This is should be set from all OneSignal entry points
* @param newAppId - String app id associated with the OneSignal dashboard app
*/
public static void setAppId(@NonNull String newAppId) {
if (newAppId == null || newAppId.isEmpty()) {
logger.warning("setAppId called with id: " + newAppId + ", ignoring!");
return;
} else if (!newAppId.equals(appId)) {
// Pre-check on app id to make sure init of SDK is performed properly
// Usually when the app id is changed during runtime so that SDK is reinitialized properly
initDone = false;
logger.verbose("setAppId called with id: " + newAppId + " changing id from: " + appId);
}
appId = newAppId;
if (appContext == null) {
logger.warning("appId set, but please call initWithContext(appContext) with Application context to complete OneSignal init!");
return;
}
if (appActivity != null && appActivity.get() != null)
init(appActivity.get());
else
init(appContext);
}
/**
* 1/2 steps in OneSignal init, relying on setAppId (usage order does not matter)
* Sets the global shared ApplicationContext for OneSignal
* This is should be set from all OneSignal entry points
* - BroadcastReceivers, Services, and Activities
* @param context - Context used by the Application of the app
*/
public static void initWithContext(@NonNull Context context) {
if (context == null) {
logger.warning("initWithContext called with null context, ignoring!");
return;
}
boolean wasAppContextNull = (appContext == null);
appContext = context.getApplicationContext();
if (context instanceof Activity)
appActivity = new WeakReference<>((Activity) context);
setupContextListeners(wasAppContextNull);
setupPrivacyConsent(appContext);
if (appId == null) {
// Get the cached app id, if it exists
String oldAppId = getSavedAppId();
if (oldAppId == null) {
logger.warning("appContext set, but please call setAppId(appId) with a valid appId to complete OneSignal init!");
} else {
logger.verbose("appContext set and cached app id found, calling setAppId with: " + oldAppId);
setAppId(oldAppId);
}
return;
} else {
logger.verbose("initWithContext called with: " + context);
}
init(context);
}
static void setRemoteNotificationReceivedHandler(OSRemoteNotificationReceivedHandler callback) {
if (remoteNotificationReceivedHandler == null)
remoteNotificationReceivedHandler = callback;
}
public static void setNotificationWillShowInForegroundHandler(@Nullable OSNotificationWillShowInForegroundHandler callback) {
notificationWillShowInForegroundHandler = callback;
}
public static void setNotificationOpenedHandler(@Nullable OSNotificationOpenedHandler callback) {
notificationOpenedHandler = callback;
if (initDone && notificationOpenedHandler != null)
fireCallbackForOpenedNotifications();
}
public static void setInAppMessageClickHandler(@Nullable OSInAppMessageClickHandler callback) {
inAppMessageClickHandler = callback;
}
/**
* Called after setAppId and initWithContext, depending on which one is called last (order does not matter)
*/
synchronized private static void init(Context context) {
logger.verbose("Starting OneSignal initialization!");
OSNotificationController.setupNotificationServiceExtension(appContext);
if (requiresUserPrivacyConsent() || !remoteParamController.isRemoteParamsCallDone()) {
if (!remoteParamController.isRemoteParamsCallDone())
logger.verbose("OneSignal SDK initialization delayed, " +
"waiting for remote params.");
else
logger.verbose("OneSignal SDK initialization delayed, " +
"waiting for privacy consent to be set.");
delayedInitParams = new DelayedConsentInitializationParameters(context, appId);
String lastAppId = appId;
// Set app id null since OneSignal was not init fully
appId = null;
// Wrapper SDK's call init twice and pass null as the appId on the first call
// the app ID is required to download parameters, so do not download params until the appID is provided
if (lastAppId != null && context != null)
makeAndroidParamsRequest(lastAppId, getUserId(), false);
return;
}
// Keep last subscribed Status if already set
subscribableStatus = subscribableStatus != Integer.MAX_VALUE ? subscribableStatus : osUtils.initializationChecker(appContext, appId);
if (isSubscriptionStatusUninitializable())
return;
if (initDone) {
if (notificationOpenedHandler != null)
fireCallbackForOpenedNotifications();
logger.debug("OneSignal SDK initialization already completed.");
return;
}
handleActivityLifecycleHandler(context);
// Clean saved init activity
appActivity = null;
OneSignalStateSynchronizer.initUserState();
// Check and handle app id change of the current session
handleAppIdChange();
// Verify the session is an Amazon purchase and track it
handleAmazonPurchase();
OSPermissionChangedInternalObserver.handleInternalChanges(getCurrentPermissionState(appContext));
// When the session reaches timeout threshold, start new session
// This is where the LocationGMS prompt is triggered and shown to the user
doSessionInit();
if (notificationOpenedHandler != null)
fireCallbackForOpenedNotifications();
if (TrackGooglePurchase.CanTrack(appContext))
trackGooglePurchase = new TrackGooglePurchase(appContext);
if (TrackFirebaseAnalytics.CanTrack())
trackFirebaseAnalytics = new TrackFirebaseAnalytics(appContext);
initDone = true;
OneSignal.Log(LOG_LEVEL.VERBOSE, "OneSignal SDK initialization done.");
outcomeEventsController.sendSavedOutcomes();
// Clean up any pending tasks that were queued up before initialization
taskController.startPendingTasks();
}
static void onRemoteParamSet() {
boolean initDelayed = reassignDelayedInitParams();
if (!initDelayed && inForeground) // Remote Params called from onAppFocus
onAppFocusLogic();
}
private static void setupContextListeners(boolean wasAppContextNull) {
// Register the lifecycle listener of the app for state changes in activities with proper context
ActivityLifecycleListener.registerActivityLifecycleCallbacks((Application) appContext);
// Do work here that should only happen once or at the start of a new lifecycle
if (wasAppContextNull) {
if (outcomeEventsFactory == null)
outcomeEventsFactory = new OSOutcomeEventsFactory(logger, apiClient, getDBHelperInstance(), preferences);
sessionManager.initSessionFromCache();
outcomeEventsController = new OSOutcomeEventsController(sessionManager, outcomeEventsFactory);
// Prefs require a context to save
// If the previous state of appContext was null, kick off write in-case it was waiting
OneSignalPrefs.startDelayedWrite();
// Cleans out old cached data to prevent over using the storage on devices
OneSignalCacheCleaner.cleanOldCachedData(appContext);
}
}
private static void setupPrivacyConsent(Context context) {
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;
// Read the current privacy consent setting from AndroidManifest.xml
String requireSetting = bundle.getString("com.onesignal.PrivacyConsent");
setRequiresUserPrivacyConsent("ENABLE".equalsIgnoreCase(requireSetting));
} catch (Throwable t) {
t.printStackTrace();
}
}
private static void handleAppIdChange() {
// Re-register user if the app id changed (might happen when a dev is testing)
String oldAppId = getSavedAppId();
if (oldAppId != null) {
if (!oldAppId.equals(appId)) {
Log(LOG_LEVEL.DEBUG, "App id has changed:\nFrom: " + oldAppId + "\n To: " + appId + "\nClearing the user id, app state, and remoteParams as they are no longer valid");
saveAppId(appId);
OneSignalStateSynchronizer.resetCurrentState();
remoteParamController.clearRemoteParams();
}
} else {
// First time setting an app id
Log(LOG_LEVEL.DEBUG, "App id set for first time: " + appId);
BadgeCountUpdater.updateCount(0, appContext);
saveAppId(appId);
}
}
public static boolean userProvidedPrivacyConsent() {
return remoteParamController.getSavedUserConsentStatus();
}
private static boolean isSubscriptionStatusUninitializable() {
return subscribableStatus == OSUtils.UNINITIALIZABLE_STATUS;
}
private static void handleActivityLifecycleHandler(Context context) {
ActivityLifecycleHandler activityLifecycleHandler = ActivityLifecycleListener.getActivityLifecycleHandler();
setInForeground(OneSignal.getCurrentActivity() != null || context instanceof Activity);
logger.debug("OneSignal handleActivityLifecycleHandler inForeground: " + inForeground);
if (inForeground) {
if (OneSignal.getCurrentActivity() == null && activityLifecycleHandler != null) {
activityLifecycleHandler.setCurActivity((Activity) context);
activityLifecycleHandler.setNextResumeIsFirstActivity(true);
}
OSNotificationRestoreWorkManager.beginEnqueueingWork(context, false);
focusTimeController.appForegrounded();
} else if (activityLifecycleHandler != null) {
activityLifecycleHandler.setNextResumeIsFirstActivity(true);
}
}
private static void handleAmazonPurchase() {
try {
Class.forName("com.amazon.device.iap.PurchasingListener");
trackAmazonPurchase = new TrackAmazonPurchase(appContext);
} catch (ClassNotFoundException e) {}
}
// If the app is not in the inForeground yet do not make an on_session call yet.
// If we don't have a OneSignal player_id yet make the call to create it regardless of focus
private static void doSessionInit() {
// Check session time to determine whether to start a new session or not
if (shouldStartNewSession()) {
logger.debug("Starting new session with appEntryState: " + getAppEntryState());
OneSignalStateSynchronizer.setNewSession();
outcomeEventsController.cleanOutcomes();
sessionManager.restartSessionIfNeeded(getAppEntryState());
getInAppMessageController().resetSessionLaunchTime();
setLastSessionTime(time.getCurrentTimeMillis());
} else if (isInForeground()) {
logger.debug("Continue on same session with appEntryState: " + getAppEntryState());
sessionManager.attemptSessionUpgrade(getAppEntryState());
}
getInAppMessageController().initWithCachedInAppMessages();
// We still want register the user to OneSignal if the SDK was initialized
// in the background for the first time.
if (!inForeground && hasUserId())
logger.debug("doSessionInit on background with already registered user");
startRegistrationOrOnSession();
}
private static void startRegistrationOrOnSession() {
if (waitingToPostStateSync)
return;
waitingToPostStateSync = true;
if (inForeground && OneSignalStateSynchronizer.getSyncAsNewSession())
locationFired = false;
startLocationUpdate();
registerForPushFired = false;
// This will also enable background player updates
if (getRemoteParams() != null)
registerForPushToken();
else
makeAndroidParamsRequest(appId, getUserId(), true);
}
private static void startLocationUpdate() {
LocationController.LocationHandler locationHandler = new LocationController.LocationHandler() {
@Override
public LocationController.PermissionType getType() {
return LocationController.PermissionType.STARTUP;
}
@Override
public void onComplete(LocationController.LocationPoint point) {
lastLocationPoint = point;
locationFired = true;
registerUser();
}
};
LocationController.getLocation(appContext, false, false, locationHandler);
}
private static PushRegistrator mPushRegistrator;
private static PushRegistrator getPushRegistrator() {
if (mPushRegistrator != null)
return mPushRegistrator;
if (OSUtils.isFireOSDeviceType())
mPushRegistrator = new PushRegistratorADM();
else if (OSUtils.isAndroidDeviceType()) {
if (OSUtils.hasFCMLibrary())
mPushRegistrator = new PushRegistratorFCM();
} else
mPushRegistrator = new PushRegistratorHMS();
return mPushRegistrator;
}
private static void registerForPushToken() {
getPushRegistrator().registerForPush(appContext, googleProjectNumber, new PushRegistrator.RegisteredHandler() {
@Override
public void complete(String id, int status) {
logger.debug("registerForPushToken completed with id: " + id + " status: " + status);
if (status < UserState.PUSH_STATUS_SUBSCRIBED) {
// Only allow errored subscribableStatuses if we have never gotten a token.