-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathMParticle.java
More file actions
1731 lines (1585 loc) · 65.7 KB
/
MParticle.java
File metadata and controls
1731 lines (1585 loc) · 65.7 KB
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.mparticle;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.mparticle.commerce.CommerceEvent;
import com.mparticle.identity.IdentityApi;
import com.mparticle.identity.IdentityApiRequest;
import com.mparticle.identity.IdentityApiResult;
import com.mparticle.identity.IdentityHttpResponse;
import com.mparticle.identity.IdentityStateListener;
import com.mparticle.identity.MParticleUser;
import com.mparticle.identity.TaskFailureListener;
import com.mparticle.identity.TaskSuccessListener;
import com.mparticle.internal.AppStateManager;
import com.mparticle.internal.ConfigManager;
import com.mparticle.internal.Constants;
import com.mparticle.internal.Constants.MessageKey;
import com.mparticle.internal.Constants.PrefKeys;
import com.mparticle.internal.DeviceAttributes;
import com.mparticle.internal.InternalSession;
import com.mparticle.internal.KitFrameworkWrapper;
import com.mparticle.internal.Logger;
import com.mparticle.internal.MPLocationListener;
import com.mparticle.internal.MPUtility;
import com.mparticle.internal.MParticleJSInterface;
import com.mparticle.internal.MessageManager;
import com.mparticle.internal.PushRegistrationHelper;
import com.mparticle.internal.database.services.MParticleDBManager;
import com.mparticle.internal.database.tables.MParticleDatabaseHelper;
import com.mparticle.internal.listeners.ApiClass;
import com.mparticle.internal.listeners.InternalListenerManager;
import com.mparticle.media.MPMediaAPI;
import com.mparticle.media.MediaCallbacks;
import com.mparticle.messaging.MPMessagingAPI;
import com.mparticle.messaging.ProviderCloudMessage;
import com.mparticle.segmentation.SegmentListener;
import com.mparticle.uploadbatching.UploadBatchReceiver;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import java.io.File;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* The primary access point to the mParticle SDK. In order to use this class, you must first call {@link #start(MParticleOptions)}. You can then retrieve a reference
* to an instance of this class via {@link #getInstance()}.
*/
@ApiClass
public class MParticle {
/**
* Used to delegate messages, events, user actions, etc on to embedded kits.
*/
@NonNull
protected KitFrameworkWrapper mKitManager;
/**
* The state manager is primarily concerned with Activity lifecycle and app visibility in order to manage sessions,
* automatically log screen views, and pass lifecycle information on top embedded kits.
*/
@NonNull
protected AppStateManager mAppStateManager;
@NonNull
protected ConfigManager mConfigManager;
@NonNull
protected MessageManager mMessageManager;
private static volatile MParticle instance;
@NonNull
protected SharedPreferences mPreferences;
@NonNull
protected MPLocationListener mLocationListener;
@NonNull
protected Context mAppContext;
@NonNull
protected MPMessagingAPI mMessaging;
@NonNull
protected MPMediaAPI mMedia;
@NonNull
protected MParticleDBManager mDatabaseManager;
@NonNull
protected volatile AttributionListener mAttributionListener;
@NonNull
protected IdentityApi mIdentityApi;
static volatile boolean sAndroidIdEnabled = false;
static volatile boolean sDevicePerformanceMetricsDisabled;
@NonNull
protected boolean locationTrackingEnabled = false;
@NonNull
protected Internal mInternal = new Internal();
private IdentityStateListener mDeferredModifyPushRegistrationListener;
@NonNull
private WrapperSdkVersion wrapperSdkVersion = new WrapperSdkVersion(WrapperSdk.WrapperNone, null);
protected MParticle() {
}
private MParticle(MParticleOptions options) {
ConfigManager configManager = new ConfigManager(options);
configManager.setUploadInterval(options.getUploadInterval());
configManager.setSessionTimeout(options.getSessionTimeout());
configManager.setIdentityConnectionTimeout(options.getConnectionTimeout());
AppStateManager appStateManager = new AppStateManager(options.getContext());
appStateManager.setConfigManager(configManager);
mAppContext = options.getContext();
mConfigManager = configManager;
mAppStateManager = appStateManager;
mDatabaseManager = new MParticleDBManager(mAppContext, options);
if (options.isUncaughtExceptionLoggingEnabled()) {
enableUncaughtExceptionLogging();
} else {
disableUncaughtExceptionLogging();
}
mMessageManager = new MessageManager(configManager, appStateManager, mKitManager, sDevicePerformanceMetricsDisabled, mDatabaseManager, options);
mConfigManager.setNetworkOptions(options.getNetworkOptions());
mPreferences = options.getContext().getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE);
UploadBatchReceiver receiver = new UploadBatchReceiver();
IntentFilter intentFilter = UploadBatchReceiver.Companion.getIntentFilter();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
mAppContext.registerReceiver(receiver, intentFilter, Context.RECEIVER_EXPORTED);
} else {
mAppContext.registerReceiver(receiver, intentFilter);
}
}
/**
* Update interval time in seconds.
* If the interval is greater or equal than 1 and different from the previous interval time,
* force uploading the messages and setting the new interval time for the future
*
* @param interval in seconds
*/
public void setUpdateInterval(int interval) {
long intervalMillis = interval * 1000L;
if ((intervalMillis >= 1 && mConfigManager.getUploadInterval() != intervalMillis)) {
upload();
mConfigManager.setUploadInterval(interval);
}
}
/**
* Start the mParticle SDK and begin tracking a user session. This method must be called prior to {@link #getInstance()}.
*
* @param options Required to initialize the SDK properly
*/
public static void start(@NonNull MParticleOptions options) {
MParticle.getInstance(options.getContext(), options);
}
/**
* Initialize or return a thread-safe instance of the mParticle SDK, specifying the API credentials to use. If this
* or any other {@link #getInstance()} has already been called in the application's lifecycle, the
* API credentials will be ignored and the current instance will be returned.
*
* @param context the Activity that is creating the instance
* @return An instance of the mParticle SDK configured with your API key
*/
@NonNull
private static MParticle getInstance(@NonNull Context context, @NonNull MParticleOptions options) {
if (instance == null) {
synchronized (MParticle.class) {
if (instance == null) {
sDevicePerformanceMetricsDisabled = options.isDevicePerformanceMetricsDisabled();
sAndroidIdEnabled = options.isAndroidIdEnabled();
setLogLevel(options.getLogLevel());
Context originalContext = context;
context = context.getApplicationContext();
if (!MPUtility.checkPermission(context, Manifest.permission.INTERNET)) {
Logger.error("mParticle requires android.permission.INTERNET permission.");
}
instance = new MParticle(options);
instance.mKitManager = new KitFrameworkWrapper(options.getContext(), instance.mMessageManager, instance.Internal().getConfigManager(), instance.Internal().getAppStateManager(), options);
instance.mIdentityApi = new IdentityApi(options.getContext(), instance.mInternal.getAppStateManager(), instance.mMessageManager, instance.mConfigManager, instance.mKitManager, options.getOperatingSystem());
instance.mMessageManager.refreshConfiguration();
instance.identify(options);
if (options.hasLocationTracking()) {
MParticleOptions.LocationTracking locationTracking = options.getLocationTracking();
if (locationTracking.enabled) {
instance.enableLocationTracking(locationTracking.provider, locationTracking.minTime, locationTracking.minDistance);
} else {
instance.disableLocationTracking();
}
}
if (instance.Internal().getConfigManager().getLogUnhandledExceptions()) {
instance.enableUncaughtExceptionLogging();
}
if (options.getAttributionListener() != null) {
instance.mAttributionListener = options.getAttributionListener();
}
//There are a number of settings that don't need to be enabled right away
//queue up a delayed init and let the start() call return ASAP.
instance.mMessageManager.initConfigDelayed();
instance.mInternal.getAppStateManager().init(Build.VERSION.SDK_INT);
//We ask to be initialized in Application#onCreate, but
//if the Context is an Activity, we know we weren't, so try
//to salvage session management via simulating onActivityResume.
if (originalContext instanceof Activity) {
instance.mAppStateManager.onActivityResumed((Activity) originalContext);
}
PushRegistrationHelper.PushRegistration pushRegistration = options.getPushRegistration();
if (pushRegistration != null) {
instance.logPushRegistration(pushRegistration.instanceId, pushRegistration.senderId);
} else {
//Check if Push InstanceId was updated since we last started the SDK and send corresponding modify() request.
String oldInstanceId = instance.mConfigManager.getPushInstanceIdBackground();
if (oldInstanceId != null) {
String newInstanceId = instance.mConfigManager.getPushInstanceId();
instance.updatePushToken(newInstanceId, oldInstanceId);
instance.mConfigManager.clearPushRegistrationBackground();
}
}
instance.mConfigManager.onMParticleStarted();
}
}
}
return instance;
}
/**
* Retrieve an instance of the MParticle class. {@link #start(MParticleOptions)} must
* be called prior to this.
*
* @return An instance of the mParticle SDK configured with your API key
*/
@Nullable
public static MParticle getInstance() {
if (instance == null) {
Logger.debug("Failed to get MParticle instance, getInstance() called prior to start().");
return null;
}
return getInstance(null, null);
}
/**
* Use this method for your own unit testing. Using a framework such as Mockito, or
* by extending MParticle, use this method to set a mock of mParticle.
*
* @param instance
*/
public static void setInstance(@Nullable MParticle instance) {
MParticle.instance = instance;
}
/**
* @return false if Android ID collection is enabled. (true by default)
* @see MParticleOptions.Builder#androidIdEnabled(boolean)
* @deprecated This method has been replaced as the behavior has been inverted - Android ID collection is now disabled by default.
* <p> Use {@link MParticle#isAndroidIdEnabled()} instead.
* <p>
* <p>
* Query the status of Android ID collection.
* <p>
* By default, the SDK will NOT collect <a href="http://developer.android.com/reference/android/provider/Settings.Secure.html#ANDROID_ID">Android Id</a> for the purpose
* of anonymous analytics. If you're not using an mParticle integration that consumes Android ID and you would like to collect it, use this API to enable collection
*/
@Deprecated
public static boolean isAndroidIdDisabled() {
return !sAndroidIdEnabled;
}
/**
* Query the status of Android ID collection.
* <p>
* By default, the SDK will NOT collect <a href="http://developer.android.com/reference/android/provider/Settings.Secure.html#ANDROID_ID">Android Id</a> for the purpose
* of anonymous analytics. If you're not using an mParticle integration that consumes Android ID and you would like to collect it, use this API to enable collection.
*
* @return true if Android ID collection is enabled. (false by default)
* @see MParticleOptions.Builder#androidIdEnabled(boolean)
*/
public static boolean isAndroidIdEnabled() {
return sAndroidIdEnabled;
}
/**
* Returns the wrapper sdk version
*
* @return
*/
public WrapperSdkVersion getWrapperSdkVersion() {
return wrapperSdkVersion;
}
/**
* Set wrapper sdk, by default NONE.
* This can only be set once.
*
* @param wrapperSdk diffent from {@link WrapperSdk.NONE}
* @param version
*/
public void setWrapperSdk(@NotNull WrapperSdk wrapperSdk, @NotNull String version) {
if (this.wrapperSdkVersion.getSdk() == WrapperSdk.WrapperNone && (wrapperSdk != WrapperSdk.WrapperNone && !version.isEmpty())) {
this.wrapperSdkVersion = new WrapperSdkVersion(wrapperSdk, version);
}
}
/**
* Set the device's current IMEI.
* <p>
* The mParticle SDK does not collect IMEI but you may use this API to provide it.
* Collecting the IMEI is generally unnecessary and discouraged for apps in Google Play. For
* apps distributed outside of Google Play, IMEI may be necessary for accurate install attribution.
* <p>
* The mParticle SDK does not persist this value - it must be set whenever the SDK is initialized.
*
* @param deviceImei a string representing the device's current IMEI, or null to remove clear it.
*/
public static void setDeviceImei(@Nullable String deviceImei) {
DeviceAttributes.setDeviceImei(deviceImei);
}
/**
* Get the device's current IMEI.
* <p>
* The mParticle SDK does not collect IMEI but you may use the {@link #setDeviceImei(String)} API to provide it..
* Collecting the IMEI is generally unnecessary and discouraged for apps in Google Play. For
* apps distributed outside of Google Play, IMEI may be necessary for accurate install attribution.
* <p>
* The mParticle SDK does not persist this value - it must be set whenever the SDK is initialized.
*
* @return a string representing the device's current IMEI, or null if not set.
*/
@Nullable
public static String getDeviceImei() {
return DeviceAttributes.getDeviceImei();
}
/**
* Query whether device performance metrics are disabled
*
* @return true if Device Performance Metrics are disabled
*/
public boolean isDevicePerformanceMetricsDisabled() {
return mMessageManager.isDevicePerformanceMetricsDisabled();
}
/**
* Explicitly terminate the current user's session.
*/
private void endSession() {
if (mConfigManager.isEnabled()) {
mAppStateManager.getSession().mLastEventTime = System.currentTimeMillis();
mAppStateManager.endSession();
}
}
/**
* Query for a read-only Session API object.
*/
@Nullable
public Session getCurrentSession() {
InternalSession session = mAppStateManager.getSession();
if (session == null || !session.isActive() || session.isTimedOut(mConfigManager.getSessionTimeout())) {
return null;
} else {
return new Session(session.mSessionID, session.mSessionStartTime);
}
}
boolean isSessionActive() {
return mAppStateManager.getSession().isActive();
}
/**
* Force upload all queued messages to the mParticle server.
*/
public void upload() {
mMessageManager.doUpload();
}
/**
* Manually set the install referrer. This will replace any install referrer that was
* automatically retrieved upon installation from Google Play.
*/
public void setInstallReferrer(@Nullable String referrer) {
InstallReferrerHelper.setInstallReferrer(mAppContext, referrer);
}
/**
* Retrieve the current install referrer, if it has been set.
*
* @return The current Install Referrer
*/
@Nullable
public String getInstallReferrer() {
return InstallReferrerHelper.getInstallReferrer(mAppContext);
}
public void logEvent(@NonNull BaseEvent event) {
if (event instanceof MPEvent && event.isShouldUploadEvent()) {
logMPEvent((MPEvent) event);
} else if (event instanceof CommerceEvent && event.isShouldUploadEvent()) {
logCommerceEvent((CommerceEvent) event);
} else {
if (mConfigManager.isEnabled()) {
mAppStateManager.ensureActiveSession();
Logger.debug("Logged event - \n", event.toString());
mKitManager.logEvent(event);
}
}
}
/**
* Log an event with an {@link MPEvent} object.
*
* @param event the event object to log
*/
private void logMPEvent(@NonNull MPEvent event) {
if (mConfigManager.isEnabled()) {
mAppStateManager.ensureActiveSession();
mMessageManager.logEvent(event, mAppStateManager.getCurrentActivityName());
Logger.debug("Logged event - \n", event.toString());
mKitManager.logEvent(event);
}
}
/**
* Log an e-Commerce related event with a {@link CommerceEvent} object.
*
* @param event the event to log
* @see CommerceEvent
*/
private void logCommerceEvent(@NonNull CommerceEvent event) {
if (mConfigManager.isEnabled()) {
mAppStateManager.ensureActiveSession();
mMessageManager.logEvent(event);
Logger.debug("Logged commerce event - \n", event.toString());
mKitManager.logEvent(event);
}
}
/**
* Logs an increase in the lifetime value of a user. This will signify an increase
* in the revenue assigned to this user for service providers that support revenue tracking.
*
* @param valueIncreased The currency value by which to increase the current user's LTV (required)
* @param eventName An event name to be associated with this increase in LTV (optional)
* @param contextInfo An MPProduct or any set of data to associate with this increase in LTV (optional)
*/
public void logLtvIncrease(@NonNull BigDecimal valueIncreased, @Nullable String eventName, @Nullable Map<String, String> contextInfo) {
if (valueIncreased == null) {
Logger.error("ValueIncreased must not be null.");
return;
}
if (contextInfo == null) {
contextInfo = new HashMap<String, String>();
}
contextInfo.put(MessageKey.RESERVED_KEY_LTV, valueIncreased.toPlainString());
contextInfo.put(Constants.MethodName.METHOD_NAME, Constants.MethodName.LOG_LTV);
logEvent(
new MPEvent.Builder(eventName == null ? "Increase LTV" : eventName, EventType.Transaction)
.customAttributes(contextInfo)
.build()
);
}
/**
* Logs a screen view event.
*
* @param screenName the name of the screen to be tracked
*/
public void logScreen(@NonNull String screenName) {
logScreen(screenName, null);
}
/**
* Logs a screen view event.
*
* @param screenName the name of the screen to be tracked
* @param eventData a Map of data attributes to associate with this screen view
*/
public void logScreen(@NonNull String screenName, @Nullable Map<String, String> eventData) {
logScreen(screenName, eventData, true);
}
/**
* Logs a screen view event.
*
* @param screenName the name of the screen to be tracked
* @param eventData a Map of data attributes to associate with this screen view
* @param shouldUploadEvent A boolean flag that indicates whether this screen event should be uploaded to mParticle when logged or only passed to kits
*/
public void logScreen(@NonNull String screenName, @Nullable Map<String, String> eventData, @NonNull Boolean shouldUploadEvent) {
logScreen(new MPEvent.Builder(screenName).shouldUploadEvent(shouldUploadEvent).customAttributes(eventData).build().setScreenEvent(true));
}
/**
* Logs a screen view event.
*
* @param screenEvent an event object, the name of the event will be used as the screen name
*/
public void logScreen(@NonNull MPEvent screenEvent) {
screenEvent.setScreenEvent(true);
if (MPUtility.isEmpty(screenEvent.getEventName())) {
Logger.error("screenName is required for logScreen.");
return;
}
if (screenEvent.getEventName().length() > Constants.LIMIT_ATTR_KEY) {
Logger.error("The screen name was too long. Discarding event.");
return;
}
mAppStateManager.ensureActiveSession();
if (mConfigManager.isEnabled() && screenEvent.isShouldUploadEvent()) {
mMessageManager.logScreen(screenEvent, screenEvent.getNavigationDirection());
Logger.debug("Logged screen: ", screenEvent.toString());
}
if (screenEvent.getNavigationDirection()) {
mKitManager.logScreen(screenEvent);
}
}
/**
* Leave a breadcrumb to be included with error and exception logging, as well as
* with regular session events.
*
* @param breadcrumb
*/
public void leaveBreadcrumb(@NonNull String breadcrumb) {
if (mConfigManager.isEnabled()) {
if (MPUtility.isEmpty(breadcrumb)) {
Logger.error("breadcrumb is required for leaveBreadcrumb.");
return;
}
if (breadcrumb.length() > Constants.LIMIT_ATTR_KEY) {
Logger.error("The breadcrumb name was too long. Discarding event.");
return;
}
mAppStateManager.ensureActiveSession();
mMessageManager.logBreadcrumb(breadcrumb);
Logger.debug("Logged breadcrumb: " + breadcrumb);
mKitManager.leaveBreadcrumb(breadcrumb);
}
}
/**
* Logs an error event.
*
* @param message the name of the error event to be tracked
*/
public void logError(@NonNull String message) {
logError(message, null);
}
/**
* Logs an error event
*
* @param message the name of the error event to be tracked
* @param errorAttributes a Map of data attributes to associate with this error
*/
public void logError(@NonNull String message, @Nullable Map<String, String> errorAttributes) {
if (mConfigManager.isEnabled()) {
if (MPUtility.isEmpty(message)) {
Logger.error("message is required for logErrorEvent.");
return;
}
mAppStateManager.ensureActiveSession();
JSONObject eventDataJSON = MPUtility.enforceAttributeConstraints(errorAttributes);
mMessageManager.logErrorEvent(message, null, eventDataJSON);
Logger.debug("Logged error with message: " + (message == null ? "<none>" : message) +
" with data: " + (eventDataJSON == null ? "<none>" : eventDataJSON.toString())
);
mKitManager.logError(message, errorAttributes);
}
}
public void logNetworkPerformance(@NonNull String url, long startTime, @NonNull String method, long length, long bytesSent, long bytesReceived, @Nullable String requestString, int responseCode) {
if (mConfigManager.isEnabled()) {
mAppStateManager.ensureActiveSession();
mMessageManager.logNetworkPerformanceEvent(startTime, method, url, length, bytesSent, bytesReceived, requestString);
mKitManager.logNetworkPerformance(url, startTime, method, length, bytesSent, bytesReceived, requestString, responseCode);
}
}
/**
* Logs an Exception.
*
* @param exception an Exception
*/
public void logException(@NonNull Exception exception) {
logException(exception, null, null);
}
/**
* Logs an Exception.
*
* @param exception an Exception
* @param eventData a Map of data attributes
*/
public void logException(@NonNull Exception exception, @Nullable Map<String, String> eventData) {
logException(exception, eventData, null);
}
/**
* Clears the current Attribution Listener.
*/
public void removeAttributionListener() {
mAttributionListener = null;
}
/**
* Retrieve the current Attribution Listener.
*/
@Nullable
public AttributionListener getAttributionListener() {
return mAttributionListener;
}
/**
* Queries the attribution results.
*
* @return the current attribution results
*/
@NonNull
public Map<Integer, AttributionResult> getAttributionResults() {
return mKitManager.getAttributionResults();
}
/**
* Logs an Exception.
*
* @param exception an Exception
* @param eventData a Map of data attributes
* @param message the name of the error event to be tracked
*/
public void logException(@NonNull Exception exception, @Nullable Map<String, String> eventData, @Nullable String message) {
if (mConfigManager.isEnabled()) {
mAppStateManager.ensureActiveSession();
JSONObject eventDataJSON = MPUtility.enforceAttributeConstraints(eventData);
mMessageManager.logErrorEvent(message, exception, eventDataJSON);
Logger.debug(
"Logged exception with message: " + (message == null ? "<none>" : message) +
" with data: " + (eventDataJSON == null ? "<none>" : eventDataJSON.toString()) +
" with exception: " + (exception == null ? "<none>" : exception.getMessage())
);
mKitManager.logException(exception, eventData, message);
}
}
/**
* Enables location tracking given a provider and update frequency criteria. The provider must
* be available and the correct permissions must have been requested within your application's manifest XML file.
*
* @param provider the provider key
* @param minTime the minimum time (in milliseconds) to trigger an update
* @param minDistance the minimum distance (in meters) to trigger an update
*/
@SuppressLint("MissingPermission")
public void enableLocationTracking(@NonNull String provider, long minTime, long minDistance) {
if (mConfigManager.isEnabled()) {
try {
LocationManager locationManager = (LocationManager) mAppContext.getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(provider)) {
Logger.error("That requested location provider is not available.");
return;
}
try {
if (null == mLocationListener) {
mLocationListener = new MPLocationListener(this);
} else {
// Clear the location listener, so it can be added again
//noinspection MissingPermission.
locationManager.removeUpdates(mLocationListener);
}
//noinspection MissingPermission
locationManager.requestLocationUpdates(provider, minTime, minDistance, mLocationListener);
locationTrackingEnabled = true;
} catch (SecurityException ignored) {
}
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString(PrefKeys.LOCATION_PROVIDER, provider)
.putLong(PrefKeys.LOCATION_MINTIME, minTime)
.putLong(PrefKeys.LOCATION_MINDISTANCE, minDistance)
.apply();
} catch (SecurityException e) {
Logger.error("The app must require the appropriate permissions to track location using this provider.");
}
}
}
/**
* Disables any mParticle location tracking that had been started.
*/
@SuppressLint("MissingPermission")
public void disableLocationTracking() {
if (mLocationListener != null) {
try {
LocationManager locationManager = (LocationManager) mAppContext.getSystemService(Context.LOCATION_SERVICE);
if (MPUtility.checkPermission(mAppContext, Manifest.permission.ACCESS_FINE_LOCATION) ||
MPUtility.checkPermission(mAppContext, Manifest.permission.ACCESS_COARSE_LOCATION)) {
try {
//noinspection MissingPermission
locationManager.removeUpdates(mLocationListener);
locationTrackingEnabled = false;
} catch (SecurityException se) {
}
}
mLocationListener = null;
SharedPreferences.Editor editor = mPreferences.edit();
editor.remove(PrefKeys.LOCATION_PROVIDER)
.remove(PrefKeys.LOCATION_MINTIME)
.remove(PrefKeys.LOCATION_MINDISTANCE)
.apply();
} catch (Exception e) {
}
}
}
/**
* Retrieves the current setting of location tracking.
*/
public boolean isLocationTrackingEnabled() {
return locationTrackingEnabled;
}
/**
* Set the current location of the active session.
*
* @param location
*/
public void setLocation(@Nullable Location location) {
mMessageManager.setLocation(location);
mKitManager.setLocation(location);
}
/**
* Set a single <i>session</i> attribute. The attribute will combined with any existing session attributes.
*
* @param key the attribute key
* @param value the attribute value. This value will be converted to its String representation as dictated by its <code>toString()</code> method.
*/
public void setSessionAttribute(@NonNull String key, @Nullable Object value) {
if (key == null) {
Logger.warning("setSessionAttribute called with null key. Ignoring...");
return;
}
if (value != null) {
value = value.toString();
}
if (mConfigManager.isEnabled()) {
mAppStateManager.ensureActiveSession();
Logger.debug("Set session attribute: " + key + "=" + value);
if (MPUtility.setCheckedAttribute(mAppStateManager.getSession().mSessionAttributes, key, value, false, false)) {
mMessageManager.setSessionAttributes();
}
}
}
/**
* Increment a single <i>session</i> attribute. If the attribute does not exist, it will be added as a new attribute.
*
* @param key the attribute key
* @param value the attribute value
*/
public void incrementSessionAttribute(@NonNull String key, int value) {
if (key == null) {
Logger.warning("incrementSessionAttribute called with null key. Ignoring...");
return;
}
if (mConfigManager.isEnabled()) {
mAppStateManager.ensureActiveSession();
Logger.debug("Incrementing session attribute: " + key + "=" + value);
if (MPUtility.setCheckedAttribute(mAppStateManager.getSession().mSessionAttributes, key, value, true, true)) {
mMessageManager.setSessionAttributes();
}
}
}
/**
* Get the current opt-out status for the application.
*
* @return the opt-out status
*/
@NonNull
public Boolean getOptOut() {
return mConfigManager.getOptedOut();
}
/**
* Control the opt-in/opt-out status for the application.
*
* @param optOutStatus set to <code>true</code> to opt out of event tracking
*/
public void setOptOut(@NonNull Boolean optOutStatus) {
if (optOutStatus != null) {
if (optOutStatus != mConfigManager.getOptedOut()) {
if (!optOutStatus) {
mAppStateManager.ensureActiveSession();
}
mMessageManager.optOut(System.currentTimeMillis(), optOutStatus);
if (optOutStatus && isSessionActive()) {
endSession();
}
mConfigManager.setOptOut(optOutStatus);
Logger.debug("Set opt-out: " + optOutStatus);
}
mKitManager.setOptOut(optOutStatus);
}
}
/**
* Retrieve a URL to be loaded within a {@link WebView} to show the user a survey
* or feedback form.
*
* @param kitId The ID of the desired survey/feedback service.
* @return a fully-formed URI, or null if no URL exists for the given ID.
* @see MParticle.ServiceProviders
*/
@Nullable
public Uri getSurveyUrl(final int kitId) {
return mKitManager.getSurveyUrl(kitId, null, null);
}
/**
* Get the current Environment that the SDK has interpreted. Will never return AutoDetect.
*
* @return the current environment, either production or development
*/
@NonNull
public Environment getEnvironment() {
return ConfigManager.getEnvironment();
}
/**
* Enable mParticle exception handling to automatically log events on uncaught exceptions.
*/
public void enableUncaughtExceptionLogging() {
mConfigManager.enableUncaughtExceptionLogging(true);
}
/**
* Disables mParticle exception handling and restores the original UncaughtExceptionHandler.
*/
public void disableUncaughtExceptionLogging() {
mConfigManager.disableUncaughtExceptionLogging(true);
}
/**
* @return The current setting of automatic screen tracking.
* @deprecated Retrieves the current setting of automatic screen tracking.
*/
@NonNull
@Deprecated
public Boolean isAutoTrackingEnabled() {
return false;
}
/**
* Retrieves the current session timeout setting in seconds
*
* @return The current session timeout setting in seconds
*/
public int getSessionTimeout() {
return mConfigManager.getSessionTimeout() / 1000;
}
public void getUserSegments(long timeout, @NonNull String endpointId, @NonNull SegmentListener listener) {
if (mMessageManager != null && mMessageManager.mUploadHandler != null) {
mMessageManager.mUploadHandler.fetchSegments(timeout, endpointId, listener);
}
}
/**
* Instrument a WebView so that communication can be facilitated between this Native SDK instance and any
* instance of the mParticle Javascript SDK is loaded within the provided WebView.
*
* @param webView
*/
@SuppressLint("AddJavascriptInterface")
@RequiresApi(17)
public void registerWebView(@NonNull WebView webView) {
registerWebView(webView, null);
}
/**
* Instrument a WebView so that communication can be facilitated between this Native SDK instance and any
* instance of the mParticle Javascript SDK is loaded within the provided WebView. Additionally,
* the "reqiredBridgeName" value will override the generated token which is used by the Javascript SDK
* to ensure communication only happens across matching Workspaces.
* <p>
* Make sure you know what you are doing when you provide a requiredBridgeName, since a mismatch
* with the Javascript SDK's bridgeName will result in a failure for it to forward calls to the Native SDK
*
* @param webView
* @param requiredBridgeName
*/
@SuppressLint("AddJavascriptInterface")
@RequiresApi(17)
public void registerWebView(@NonNull WebView webView, String requiredBridgeName) {
MParticleJSInterface.registerWebView(webView, requiredBridgeName);
}
/**
* Set the minimum log level before the SDK is initialized. The log level
* is used to moderate the amount of messages that are printed by the SDK
* to the console. Note that while the SDK is in the Production,
* <i>log messages at or above this level will be printed</i>.
*
* @param level
* @see MParticle.LogLevel
*/
public static void setLogLevel(@NonNull LogLevel level) {
if (level != null) {
Logger.setMinLogLevel(level, true);
}
}
/**
* Entry point to the Messaging APIs.
*
* @return a helper object that allows for interaction with the Messaging APIs
*/
@NonNull
public MPMessagingAPI Messaging() {
if (mMessaging == null) {
mMessaging = new MPMessagingAPI(mAppContext);
}
return mMessaging;
}
static String getAppState() {
String appState = AppStateManager.APP_STATE_NOTRUNNING;
if (AppStateManager.mInitialized) {
MParticle instance = MParticle.getInstance();
if (instance != null) {
if (instance.mAppStateManager.isBackgrounded()) {
appState = AppStateManager.APP_STATE_BACKGROUND;
} else {
appState = AppStateManager.APP_STATE_FOREGROUND;
}
}
}
return appState;
}
/**
* Entry point to the Media APIs.
*
* @return a helper object that allows for interaction with the Media APIs
*/
@NonNull
public MPMediaAPI Media() {
if (mMedia == null) {
mMedia = new MPMediaAPI(mAppContext, new MediaCallbacks() {
@Override
public void onAudioPlaying() {
mAppStateManager.ensureActiveSession();
}
@Override
public void onAudioStopped() {
try {
mAppStateManager.getSession().mLastEventTime = System.currentTimeMillis();
} catch (Exception e) {
}
}
});
}