-
Notifications
You must be signed in to change notification settings - Fork 363
/
MixpanelAPI.java
2325 lines (2112 loc) · 99.6 KB
/
MixpanelAPI.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.mixpanel.android.mpmetrics;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import com.mixpanel.android.util.MPLog;
import com.mixpanel.android.util.ProxyServerInteractor;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import java.util.concurrent.Future;
/**
* Core class for interacting with Mixpanel Analytics.
*
* <p>Call {@link #getInstance(Context, String, boolean)} with
* your main application activity and your Mixpanel API token as arguments
* an to get an instance you can use to report how users are using your
* application.
*
* <p>Once you have an instance, you can send events to Mixpanel
* using {@link #track(String, JSONObject)}, and update People Analytics
* records with {@link #getPeople()}
*
* <p>The Mixpanel library will periodically send information to
* Mixpanel servers, so your application will need to have
* <code>android.permission.INTERNET</code>. In addition, to preserve
* battery life, messages to Mixpanel servers may not be sent immediately
* when you call {@link #track(String)}or {@link People#set(String, Object)}.
* The library will send messages periodically throughout the lifetime
* of your application, but you will need to call {@link #flush()}
* before your application is completely shutdown to ensure all of your
* events are sent.
*
* <p>A typical use-case for the library might look like this:
*
* <pre>
* {@code
* public class MainActivity extends Activity {
* MixpanelAPI mMixpanel;
*
* public void onCreate(Bundle saved) {
* mMixpanel = MixpanelAPI.getInstance(this, "YOUR MIXPANEL API TOKEN");
* ...
* }
*
* public void whenSomethingInterestingHappens(int flavor) {
* JSONObject properties = new JSONObject();
* properties.put("flavor", flavor);
* mMixpanel.track("Something Interesting Happened", properties);
* ...
* }
*
* public void onDestroy() {
* mMixpanel.flush();
* super.onDestroy();
* }
* }
* }
* </pre>
*
* <p>In addition to this documentation, you may wish to take a look at
* <a href="https://github.com/mixpanel/sample-android-mixpanel-integration">the Mixpanel sample Android application</a>.
* It demonstrates a variety of techniques, including
* updating People Analytics records with {@link People} and others.
*
* <p>There are also <a href="https://mixpanel.com/docs/">step-by-step getting started documents</a>
* available at mixpanel.com
*
* @see <a href="https://mixpanel.com/docs/integration-libraries/android">getting started documentation for tracking events</a>
* @see <a href="https://mixpanel.com/docs/people-analytics/android">getting started documentation for People Analytics</a>
* @see <a href="https://github.com/mixpanel/sample-android-mixpanel-integration">The Mixpanel Android sample application</a>
*/
public class MixpanelAPI {
/**
* String version of the library.
*/
public static final String VERSION = MPConfig.VERSION;
/**
* You shouldn't instantiate MixpanelAPI objects directly.
* Use MixpanelAPI.getInstance to get an instance.
*/
MixpanelAPI(Context context, Future<SharedPreferences> referrerPreferences, String token, boolean optOutTrackingDefault, JSONObject superProperties, boolean trackAutomaticEvents) {
this(context, referrerPreferences, token, MPConfig.getInstance(context, null), optOutTrackingDefault, superProperties, null, trackAutomaticEvents);
}
/**
* You shouldn't instantiate MixpanelAPI objects directly.
* Use MixpanelAPI.getInstance to get an instance.
*/
MixpanelAPI(Context context, Future<SharedPreferences> referrerPreferences, String token, boolean optOutTrackingDefault, JSONObject superProperties, String instanceName, boolean trackAutomaticEvents) {
this(context, referrerPreferences, token, MPConfig.getInstance(context, instanceName), optOutTrackingDefault, superProperties, instanceName, trackAutomaticEvents);
}
/**
* You shouldn't instantiate MixpanelAPI objects directly.
* Use MixpanelAPI.getInstance to get an instance.
*/
MixpanelAPI(Context context, Future<SharedPreferences> referrerPreferences, String token, MPConfig config, boolean optOutTrackingDefault, JSONObject superProperties, String instanceName, boolean trackAutomaticEvents) {
mContext = context;
mToken = token;
mInstanceName = instanceName;
mPeople = new PeopleImpl();
mGroups = new HashMap<String, GroupImpl>();
mConfig = config;
mTrackAutomaticEvents = trackAutomaticEvents;
final Map<String, String> deviceInfo = new HashMap<String, String>();
deviceInfo.put("$android_lib_version", MPConfig.VERSION);
deviceInfo.put("$android_os", "Android");
deviceInfo.put("$android_os_version", Build.VERSION.RELEASE == null ? "UNKNOWN" : Build.VERSION.RELEASE);
deviceInfo.put("$android_manufacturer", Build.MANUFACTURER == null ? "UNKNOWN" : Build.MANUFACTURER);
deviceInfo.put("$android_brand", Build.BRAND == null ? "UNKNOWN" : Build.BRAND);
deviceInfo.put("$android_model", Build.MODEL == null ? "UNKNOWN" : Build.MODEL);
try {
final PackageManager manager = mContext.getPackageManager();
final PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0);
deviceInfo.put("$android_app_version", info.versionName);
deviceInfo.put("$android_app_version_code", Integer.toString(info.versionCode));
} catch (final PackageManager.NameNotFoundException e) {
MPLog.e(LOGTAG, "Exception getting app version name", e);
}
mDeviceInfo = Collections.unmodifiableMap(deviceInfo);
mSessionMetadata = new SessionMetadata();
mMessages = getAnalyticsMessages();
mPersistentIdentity = getPersistentIdentity(context, referrerPreferences, token, instanceName);
mEventTimings = mPersistentIdentity.getTimeEvents();
if (optOutTrackingDefault && (hasOptedOutTracking() || !mPersistentIdentity.hasOptOutFlag(token))) {
optOutTracking();
}
if (superProperties != null) {
registerSuperProperties(superProperties);
}
final boolean dbExists = MPDbAdapter.getInstance(mContext, mConfig).getDatabaseFile().exists();
registerMixpanelActivityLifecycleCallbacks();
if (mPersistentIdentity.isFirstLaunch(dbExists, mToken) && mTrackAutomaticEvents) {
track(AutomaticEvents.FIRST_OPEN, null, true);
mPersistentIdentity.setHasLaunched(mToken);
}
if (sendAppOpen() && mTrackAutomaticEvents) {
track("$app_open", null);
}
if (mPersistentIdentity.isNewVersion(deviceInfo.get("$android_app_version_code")) && mTrackAutomaticEvents) {
try {
final JSONObject messageProps = new JSONObject();
messageProps.put(AutomaticEvents.VERSION_UPDATED, deviceInfo.get("$android_app_version"));
track(AutomaticEvents.APP_UPDATED, messageProps, true);
} catch (JSONException e) {}
}
if (!mConfig.getDisableExceptionHandler()) {
ExceptionHandler.init();
}
if (mConfig.getRemoveLegacyResidualFiles()) {
mMessages.removeResidualImageFiles(new File(mContext.getApplicationInfo().dataDir));
}
}
/**
* Get the instance of MixpanelAPI associated with your Mixpanel project token.
*
* <p>Use getInstance to get a reference to a shared
* instance of MixpanelAPI you can use to send events
* and People Analytics updates to Mixpanel.</p>
* <p>getInstance is thread safe, but the returned instance is not,
* and may be shared with other callers of getInstance.
* The best practice is to call getInstance, and use the returned MixpanelAPI,
* object from a single thread (probably the main UI thread of your application).</p>
* <p>If you do choose to track events from multiple threads in your application,
* you should synchronize your calls on the instance itself, like so:</p>
* <pre>
* {@code
* MixpanelAPI instance = MixpanelAPI.getInstance(context, token);
* synchronized(instance) { // Only necessary if the instance will be used in multiple threads.
* instance.track(...)
* }
* }
* </pre>
*
* @param context The application context you are tracking
* @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site,
* in the settings dialog.
* @param trackAutomaticEvents Whether or not to collect common mobile events
* include app sessions, first app opens, app updated, etc.
* @return an instance of MixpanelAPI associated with your project
*/
public static MixpanelAPI getInstance(Context context, String token, boolean trackAutomaticEvents) {
return getInstance(context, token, false, null, null, trackAutomaticEvents);
}
/**
* Get the instance of MixpanelAPI associated with your Mixpanel project token.
*
* <p>Use getInstance to get a reference to a shared
* instance of MixpanelAPI you can use to send events
* and People Analytics updates to Mixpanel.</p>
* <p>getInstance is thread safe, but the returned instance is not,
* and may be shared with other callers of getInstance.
* The best practice is to call getInstance, and use the returned MixpanelAPI,
* object from a single thread (probably the main UI thread of your application).</p>
* <p>If you do choose to track events from multiple threads in your application,
* you should synchronize your calls on the instance itself, like so:</p>
* <pre>
* {@code
* MixpanelAPI instance = MixpanelAPI.getInstance(context, token);
* synchronized(instance) { // Only necessary if the instance will be used in multiple threads.
* instance.track(...)
* }
* }
* </pre>
*
* @param context The application context you are tracking
* @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site,
* in the settings dialog.
* @param instanceName The name you want to uniquely identify the Mixpanel Instance.
* It is useful when you want more than one Mixpanel instance under the same project token
* @param trackAutomaticEvents Whether or not to collect common mobile events
* include app sessions, first app opens, app updated, etc.
* @return an instance of MixpanelAPI associated with your project
*/
public static MixpanelAPI getInstance(Context context, String token, String instanceName, boolean trackAutomaticEvents) {
return getInstance(context, token, false, null, instanceName, trackAutomaticEvents);
}
/**
* Get the instance of MixpanelAPI associated with your Mixpanel project token.
*
* <p>Use getInstance to get a reference to a shared
* instance of MixpanelAPI you can use to send events
* and People Analytics updates to Mixpanel.</p>
* <p>getInstance is thread safe, but the returned instance is not,
* and may be shared with other callers of getInstance.
* The best practice is to call getInstance, and use the returned MixpanelAPI,
* object from a single thread (probably the main UI thread of your application).</p>
* <p>If you do choose to track events from multiple threads in your application,
* you should synchronize your calls on the instance itself, like so:</p>
* <pre>
* {@code
* MixpanelAPI instance = MixpanelAPI.getInstance(context, token);
* synchronized(instance) { // Only necessary if the instance will be used in multiple threads.
* instance.track(...)
* }
* }
* </pre>
*
* @param context The application context you are tracking
* @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site,
* in the settings dialog.
* @param optOutTrackingDefault Whether or not Mixpanel can start tracking by default. See
* {@link #optOutTracking()}.
* @param trackAutomaticEvents Whether or not to collect common mobile events
* include app sessions, first app opens, app updated, etc.
* @return an instance of MixpanelAPI associated with your project
*/
public static MixpanelAPI getInstance(Context context, String token, boolean optOutTrackingDefault, boolean trackAutomaticEvents) {
return getInstance(context, token, optOutTrackingDefault, null, null, trackAutomaticEvents);
}
/**
* Get the instance of MixpanelAPI associated with your Mixpanel project token.
*
* <p>Use getInstance to get a reference to a shared
* instance of MixpanelAPI you can use to send events
* and People Analytics updates to Mixpanel.</p>
* <p>getInstance is thread safe, but the returned instance is not,
* and may be shared with other callers of getInstance.
* The best practice is to call getInstance, and use the returned MixpanelAPI,
* object from a single thread (probably the main UI thread of your application).</p>
* <p>If you do choose to track events from multiple threads in your application,
* you should synchronize your calls on the instance itself, like so:</p>
* <pre>
* {@code
* MixpanelAPI instance = MixpanelAPI.getInstance(context, token);
* synchronized(instance) { // Only necessary if the instance will be used in multiple threads.
* instance.track(...)
* }
* }
* </pre>
*
* @param context The application context you are tracking
* @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site,
* in the settings dialog.
* @param optOutTrackingDefault Whether or not Mixpanel can start tracking by default. See
* {@link #optOutTracking()}.
* @param instanceName The name you want to uniquely identify the Mixpanel Instance.
It is useful when you want more than one Mixpanel instance under the same project token.
* @param trackAutomaticEvents Whether or not to collect common mobile events
* include app sessions, first app opens, app updated, etc.
* @return an instance of MixpanelAPI associated with your project
*/
public static MixpanelAPI getInstance(Context context, String token, boolean optOutTrackingDefault, String instanceName, boolean trackAutomaticEvents) {
return getInstance(context, token, optOutTrackingDefault, null, instanceName, trackAutomaticEvents);
}
/**
* Get the instance of MixpanelAPI associated with your Mixpanel project token.
*
* <p>Use getInstance to get a reference to a shared
* instance of MixpanelAPI you can use to send events
* and People Analytics updates to Mixpanel.</p>
* <p>getInstance is thread safe, but the returned instance is not,
* and may be shared with other callers of getInstance.
* The best practice is to call getInstance, and use the returned MixpanelAPI,
* object from a single thread (probably the main UI thread of your application).</p>
* <p>If you do choose to track events from multiple threads in your application,
* you should synchronize your calls on the instance itself, like so:</p>
* <pre>
* {@code
* MixpanelAPI instance = MixpanelAPI.getInstance(context, token);
* synchronized(instance) { // Only necessary if the instance will be used in multiple threads.
* instance.track(...)
* }
* }
* </pre>
*
* @param context The application context you are tracking
* @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site,
* in the settings dialog.
* @param superProperties A JSONObject containing super properties to register.
* @param trackAutomaticEvents Whether or not to collect common mobile events
* include app sessions, first app opens, app updated, etc.
* @return an instance of MixpanelAPI associated with your project
*/
public static MixpanelAPI getInstance(Context context, String token, JSONObject superProperties, boolean trackAutomaticEvents) {
return getInstance(context, token, false, superProperties, null, trackAutomaticEvents);
}
/**
* Get the instance of MixpanelAPI associated with your Mixpanel project token.
*
* <p>Use getInstance to get a reference to a shared
* instance of MixpanelAPI you can use to send events
* and People Analytics updates to Mixpanel.</p>
* <p>getInstance is thread safe, but the returned instance is not,
* and may be shared with other callers of getInstance.
* The best practice is to call getInstance, and use the returned MixpanelAPI,
* object from a single thread (probably the main UI thread of your application).</p>
* <p>If you do choose to track events from multiple threads in your application,
* you should synchronize your calls on the instance itself, like so:</p>
* <pre>
* {@code
* MixpanelAPI instance = MixpanelAPI.getInstance(context, token);
* synchronized(instance) { // Only necessary if the instance will be used in multiple threads.
* instance.track(...)
* }
* }
* </pre>
*
* @param context The application context you are tracking
* @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site,
* in the settings dialog.
* @param superProperties A JSONObject containing super properties to register.
* @param instanceName The name you want to uniquely identify the Mixpanel Instance.
* It is useful when you want more than one Mixpanel instance under the same project token
* @param trackAutomaticEvents Whether or not to collect common mobile events
* include app sessions, first app opens, app updated, etc.
* @return an instance of MixpanelAPI associated with your project
*/
public static MixpanelAPI getInstance(Context context, String token, JSONObject superProperties, String instanceName, boolean trackAutomaticEvents) {
return getInstance(context, token, false, superProperties, instanceName, trackAutomaticEvents);
}
/**
* Get the instance of MixpanelAPI associated with your Mixpanel project token.
*
* <p>Use getInstance to get a reference to a shared
* instance of MixpanelAPI you can use to send events
* and People Analytics updates to Mixpanel.</p>
* <p>getInstance is thread safe, but the returned instance is not,
* and may be shared with other callers of getInstance.
* The best practice is to call getInstance, and use the returned MixpanelAPI,
* object from a single thread (probably the main UI thread of your application).</p>
* <p>If you do choose to track events from multiple threads in your application,
* you should synchronize your calls on the instance itself, like so:</p>
* <pre>
* {@code
* MixpanelAPI instance = MixpanelAPI.getInstance(context, token);
* synchronized(instance) { // Only necessary if the instance will be used in multiple threads.
* instance.track(...)
* }
* }
* </pre>
*
* @param context The application context you are tracking
* @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site,
* in the settings dialog.
* @param optOutTrackingDefault Whether or not Mixpanel can start tracking by default. See
* {@link #optOutTracking()}.
* @param superProperties A JSONObject containing super properties to register.
* @param instanceName The name you want to uniquely identify the Mixpanel Instance.
* It is useful when you want more than one Mixpanel instance under the same project token
* @param trackAutomaticEvents Whether or not to collect common mobile events
* include app sessions, first app opens, app updated, etc.
* @return an instance of MixpanelAPI associated with your project
*/
public static MixpanelAPI getInstance(Context context, String token, boolean optOutTrackingDefault, JSONObject superProperties, String instanceName, boolean trackAutomaticEvents) {
if (null == token || null == context) {
return null;
}
synchronized (sInstanceMap) {
final Context appContext = context.getApplicationContext();
if (null == sReferrerPrefs) {
sReferrerPrefs = sPrefsLoader.loadPreferences(context, MPConfig.REFERRER_PREFS_NAME, null);
}
String instanceKey = instanceName != null ? instanceName : token;
Map <Context, MixpanelAPI> instances = sInstanceMap.get(instanceKey);
if (null == instances) {
instances = new HashMap<Context, MixpanelAPI>();
sInstanceMap.put(instanceKey, instances);
}
MixpanelAPI instance = instances.get(appContext);
if (null == instance && ConfigurationChecker.checkBasicConfiguration(appContext)) {
instance = new MixpanelAPI(appContext, sReferrerPrefs, token, optOutTrackingDefault, superProperties, instanceName, trackAutomaticEvents);
registerAppLinksListeners(context, instance);
instances.put(appContext, instance);
}
checkIntentForInboundAppLink(context);
return instance;
}
}
/**
* Controls whether to automatically send the client IP Address as part of event tracking.
*
* <p> With an IP address, geo-location is possible down to neighborhoods within a city,
* although the Mixpanel Dashboard will just show you city level location specificity.
*
* @param useIpAddressForGeolocation If true, automatically send the client IP Address. Defaults to true.
*/
public void setUseIpAddressForGeolocation(boolean useIpAddressForGeolocation) {
mConfig.setUseIpAddressForGeolocation(useIpAddressForGeolocation);
}
/**
* Controls whether to enable the run time debug logging
*
* @param enableLogging If true, emit more detailed log messages. Defaults to false
*/
public void setEnableLogging(boolean enableLogging) {
mConfig.setEnableLogging(enableLogging);
}
/**
* Set maximum number of events/updates to send in a single network request
*
* @param flushBatchSize int, the number of events to be flushed at a time, defaults to 50
*/
public void setFlushBatchSize(int flushBatchSize) {
mConfig.setFlushBatchSize(flushBatchSize);
}
/**
* Get maximum number of events/updates to send in a single network request
*
* @return the integer number of events to be flushed at a time
*/
public int getFlushBatchSize() {
return mConfig.getFlushBatchSize();
}
/**
* Set an integer number of bytes, the maximum size limit to the Mixpanel database.
*
* @param maximumDatabaseLimit an integer number of bytes, the maximum size limit to the Mixpanel database.
*/
public void setMaximumDatabaseLimit(int maximumDatabaseLimit) {
mConfig.setMaximumDatabaseLimit(maximumDatabaseLimit);
}
/**
* Get the maximum size limit to the Mixpanel database.
*
* @return an integer number of bytes, the maximum size limit to the Mixpanel database.
*/
public int getMaximumDatabaseLimit() {
return mConfig.getMaximumDatabaseLimit();
}
/**
* Set the base URL used for Mixpanel API requests.
* Useful if you need to proxy Mixpanel requests. Defaults to https://api.mixpanel.com.
* To route data to Mixpanel's EU servers, set to https://api-eu.mixpanel.com
*
* @param serverURL the base URL used for Mixpanel API requests
*/
public void setServerURL(String serverURL) {
mConfig.setServerURL(serverURL);
}
/**
* Set the base URL used for Mixpanel API requests.
* Useful if you need to proxy Mixpanel requests. Defaults to https://api.mixpanel.com.
* To route data to Mixpanel's EU servers, set to https://api-eu.mixpanel.com
*
* @param serverURL the base URL used for Mixpanel API requests
* @param callback the callback for mixpanel proxy server api headers and status
*/
public void setServerURL(String serverURL, ProxyServerInteractor callback) {
mConfig.setServerURL(serverURL, callback);
}
public Boolean getTrackAutomaticEvents() { return mTrackAutomaticEvents; }
/**
* This function creates a distinct_id alias from alias to distinct_id. If distinct_id is null, then it will create an alias
* to the current events distinct_id, which may be the distinct_id randomly generated by the Mixpanel library
* before {@link #identify(String)} is called.
*
* <p>This call does not identify the user after. You must still call {@link #identify(String)} if you wish the new alias to be used for Events and People.
*
* @param alias the new value that should represent distinct_id.
* @param distinct_id the old distinct_id that alias will be mapped to.
*/
public void alias(String alias, String distinct_id) {
if (hasOptedOutTracking()) return;
if (distinct_id == null) {
distinct_id = getDistinctId();
}
if (alias.equals(distinct_id)) {
MPLog.w(LOGTAG, "Attempted to alias identical distinct_ids " + alias + ". Alias message will not be sent.");
return;
}
try {
final JSONObject j = new JSONObject();
j.put("alias", alias);
j.put("distinct_id", distinct_id);
track("$create_alias", j);
} catch (final JSONException e) {
MPLog.e(LOGTAG, "Failed to alias", e);
}
flush();
}
/**
* Equivalent to {@link #identify(String, boolean)} with a true argument for usePeople.
*
* <p>By default, this method will also associate future calls
* to {@link People#set(JSONObject)}, {@link People#increment(Map)}, {@link People#append(String, Object)}, etc...
* with a particular People Analytics user with the distinct id.
* If you do not want to do that, you must call {@link #identify(String, boolean)} with false for second argument.
* NOTE: This behavior changed in version 6.2.0, previously {@link People#identify(String)} had
* to be called separately.
*
* @param distinctId a string uniquely identifying this user. Events sent to
* Mixpanel or Users identified using the same distinct id will be considered associated with the
* same visitor/customer for retention and funnel reporting, so be sure that the given
* value is globally unique for each individual user you intend to track.
*/
public void identify(String distinctId) {
identify(distinctId, true);
}
/**
* Associate all future calls to {@link #track(String, JSONObject)} with the user identified by
* the given distinct id.
*
* <p>Calls to {@link #track(String, JSONObject)} made before corresponding calls to identify
* will use an anonymous locally generated distinct id, which means it is best to call identify
* early to ensure that your Mixpanel funnels and retention analytics can continue to track the
* user throughout their lifetime. We recommend calling identify when the user authenticates.
*
* <p>Once identify is called, the local distinct id persists across restarts of
* your application.
*
* @param distinctId a string uniquely identifying this user. Events sent to
* Mixpanel using the same disinct id will be considered associated with the
* same visitor/customer for retention and funnel reporting, so be sure that the given
* value is globally unique for each individual user you intend to track.
*
* @param usePeople boolean indicating whether or not to also call
* {@link People#identify(String)}
*
*/
public void identify(String distinctId, boolean usePeople) {
if (hasOptedOutTracking()) return;
if (distinctId == null) {
MPLog.e(LOGTAG, "Can't identify with null distinct_id.");
return;
}
synchronized (mPersistentIdentity) {
String currentEventsDistinctId = mPersistentIdentity.getEventsDistinctId();
if (!distinctId.equals(currentEventsDistinctId)) {
if (distinctId.startsWith("$device:")) {
MPLog.e(LOGTAG, "Can't identify with '$device:' distinct_id.");
return;
}
mPersistentIdentity.setEventsDistinctId(distinctId);
mPersistentIdentity.setAnonymousIdIfAbsent(currentEventsDistinctId);
mPersistentIdentity.markEventsUserIdPresent();
try {
JSONObject identifyPayload = new JSONObject();
identifyPayload.put("$anon_distinct_id", currentEventsDistinctId);
track("$identify", identifyPayload);
} catch (JSONException e) {
MPLog.e(LOGTAG, "Could not track $identify event");
}
}
if (usePeople) {
mPeople.identify_people(distinctId);
}
}
}
/**
* Begin timing of an event. Calling timeEvent("Thing") will not send an event, but
* when you eventually call track("Thing"), your tracked event will be sent with a "$duration"
* property, representing the number of seconds between your calls.
*
* @param eventName the name of the event to track with timing.
*/
public void timeEvent(final String eventName) {
if (hasOptedOutTracking()) return;
final long writeTime = System.currentTimeMillis();
synchronized (mEventTimings) {
mEventTimings.put(eventName, writeTime);
mPersistentIdentity.addTimeEvent(eventName, writeTime);
}
}
/**
* Clears all current event timings.
*
*/
public void clearTimedEvents() {
synchronized (mEventTimings) {
mEventTimings.clear();
mPersistentIdentity.clearTimedEvents();
}
}
/**
* Clears the event timing for an event.
*
* @param eventName the name of the timed event to clear.
*/
public void clearTimedEvent(final String eventName) {
synchronized (mEventTimings) {
mEventTimings.remove(eventName);
mPersistentIdentity.removeTimedEvent(eventName);
}
}
/**
* Retrieves the time elapsed for the named event since timeEvent() was called.
*
* @param eventName the name of the event to be tracked that was previously called with timeEvent()
*
* @return Time elapsed since {@link #timeEvent(String)} was called for the given eventName.
*/
public double eventElapsedTime(final String eventName) {
final long currentTime = System.currentTimeMillis();
Long startTime;
synchronized (mEventTimings) {
startTime = mEventTimings.get(eventName);
}
return startTime == null ? 0 : (double)((currentTime - startTime) / 1000);
}
/**
* Track an event.
*
* <p>Every call to track eventually results in a data point sent to Mixpanel. These data points
* are what are measured, counted, and broken down to create your Mixpanel reports. Events
* have a string name, and an optional set of name/value pairs that describe the properties of
* that event.
*
* @param eventName The name of the event to send
* @param properties A Map containing the key value pairs of the properties to include in this event.
* Pass null if no extra properties exist.
*
* See also {@link #track(String, org.json.JSONObject)}
*/
public void trackMap(String eventName, Map<String, Object> properties) {
if (hasOptedOutTracking()) return;
if (null == properties) {
track(eventName, null);
} else {
try {
track(eventName, new JSONObject(properties));
} catch (NullPointerException e) {
MPLog.w(LOGTAG, "Can't have null keys in the properties of trackMap!");
}
}
}
/**
* Track an event with specific groups.
*
* <p>Every call to track eventually results in a data point sent to Mixpanel. These data points
* are what are measured, counted, and broken down to create your Mixpanel reports. Events
* have a string name, and an optional set of name/value pairs that describe the properties of
* that event. Group key/value pairs are upserted into the property map before tracking.
*
* @param eventName The name of the event to send
* @param properties A Map containing the key value pairs of the properties to include in this event.
* Pass null if no extra properties exist.
* @param groups A Map containing the group key value pairs for this event.
*
* See also {@link #track(String, org.json.JSONObject)}, {@link #trackMap(String, Map)}
*/
public void trackWithGroups(String eventName, Map<String, Object> properties, Map<String, Object> groups) {
if (hasOptedOutTracking()) return;
if (null == groups) {
trackMap(eventName, properties);
} else if (null == properties) {
trackMap(eventName, groups);
} else {
for (Entry<String, Object> e : groups.entrySet()) {
if (e.getValue() != null) {
properties.put(e.getKey(), e.getValue());
}
}
trackMap(eventName, properties);
}
}
/**
* Track an event.
*
* <p>Every call to track eventually results in a data point sent to Mixpanel. These data points
* are what are measured, counted, and broken down to create your Mixpanel reports. Events
* have a string name, and an optional set of name/value pairs that describe the properties of
* that event.
*
* @param eventName The name of the event to send
* @param properties A JSONObject containing the key value pairs of the properties to include in this event.
* Pass null if no extra properties exist.
*/
public void track(String eventName, JSONObject properties) {
if (hasOptedOutTracking()) return;
track(eventName, properties, false);
}
/**
* Equivalent to {@link #track(String, JSONObject)} with a null argument for properties.
* Consider adding properties to your tracking to get the best insights and experience from Mixpanel.
* @param eventName the name of the event to send
*/
public void track(String eventName) {
if (hasOptedOutTracking()) return;
track(eventName, null);
}
/**
* Push all queued Mixpanel events and People Analytics changes to Mixpanel servers.
*
* <p>Events and People messages are pushed gradually throughout
* the lifetime of your application. This means that to ensure that all messages
* are sent to Mixpanel when your application is shut down, you will
* need to call flush() to let the Mixpanel library know it should
* send all remaining messages to the server. We strongly recommend
* placing a call to flush() in the onDestroy() method of
* your main application activity.
*/
public void flush() {
if (hasOptedOutTracking()) return;
mMessages.postToServer(new AnalyticsMessages.MixpanelDescription(mToken));
}
/**
* Returns a json object of the user's current super properties
*
*<p>SuperProperties are a collection of properties that will be sent with every event to Mixpanel,
* and persist beyond the lifetime of your application.
*
* @return Super properties for this Mixpanel instance.
*/
public JSONObject getSuperProperties() {
JSONObject ret = new JSONObject();
mPersistentIdentity.addSuperPropertiesToObject(ret);
return ret;
}
/**
* Returns the string id currently being used to uniquely identify the user. Before any calls to
* {@link #identify(String)}, this will be an id automatically generated by the library.
*
*
* @return The distinct id that uniquely identifies the current user.
*
* @see #identify(String)
*/
public String getDistinctId() {
return mPersistentIdentity.getEventsDistinctId();
}
/**
* Returns the anonymoous id currently being used to uniquely identify the device and all
* with events sent using {@link #track(String, JSONObject)} will have this id as a device
* id
*
* @return The device id associated with event tracking
*/
public String getAnonymousId() {
return mPersistentIdentity.getAnonymousId();
}
/**
* Returns the user id with which identify is called and all the with events sent using
* {@link #track(String, JSONObject)} will have this id as a user id
*
* @return The user id associated with event tracking
*/
protected String getUserId() {
return mPersistentIdentity.getEventsUserId();
}
/**
* Register properties that will be sent with every subsequent call to {@link #track(String, JSONObject)}.
*
* <p>SuperProperties are a collection of properties that will be sent with every event to Mixpanel,
* and persist beyond the lifetime of your application.
*
* <p>Setting a superProperty with registerSuperProperties will store a new superProperty,
* possibly overwriting any existing superProperty with the same name (to set a
* superProperty only if it is currently unset, use {@link #registerSuperPropertiesOnce(JSONObject)})
*
* <p>SuperProperties will persist even if your application is taken completely out of memory.
* to remove a superProperty, call {@link #unregisterSuperProperty(String)} or {@link #clearSuperProperties()}
*
* @param superProperties A Map containing super properties to register
*
* See also {@link #registerSuperProperties(org.json.JSONObject)}
*/
public void registerSuperPropertiesMap(Map<String, Object> superProperties) {
if (hasOptedOutTracking()) return;
if (null == superProperties) {
MPLog.e(LOGTAG, "registerSuperPropertiesMap does not accept null properties");
return;
}
try {
registerSuperProperties(new JSONObject(superProperties));
} catch (NullPointerException e) {
MPLog.w(LOGTAG, "Can't have null keys in the properties of registerSuperPropertiesMap");
}
}
/**
* Register properties that will be sent with every subsequent call to {@link #track(String, JSONObject)}.
*
* <p>SuperProperties are a collection of properties that will be sent with every event to Mixpanel,
* and persist beyond the lifetime of your application.
*
* <p>Setting a superProperty with registerSuperProperties will store a new superProperty,
* possibly overwriting any existing superProperty with the same name (to set a
* superProperty only if it is currently unset, use {@link #registerSuperPropertiesOnce(JSONObject)})
*
* <p>SuperProperties will persist even if your application is taken completely out of memory.
* to remove a superProperty, call {@link #unregisterSuperProperty(String)} or {@link #clearSuperProperties()}
*
* @param superProperties A JSONObject containing super properties to register
* @see #registerSuperPropertiesOnce(JSONObject)
* @see #unregisterSuperProperty(String)
* @see #clearSuperProperties()
*/
public void registerSuperProperties(JSONObject superProperties) {
if (hasOptedOutTracking()) return;
mPersistentIdentity.registerSuperProperties(superProperties);
}
/**
* Remove a single superProperty, so that it will not be sent with future calls to {@link #track(String, JSONObject)}.
*
* <p>If there is a superProperty registered with the given name, it will be permanently
* removed from the existing superProperties.
* To clear all superProperties, use {@link #clearSuperProperties()}
*
* @param superPropertyName name of the property to unregister
* @see #registerSuperProperties(JSONObject)
*/
public void unregisterSuperProperty(String superPropertyName) {
if (hasOptedOutTracking()) return;
mPersistentIdentity.unregisterSuperProperty(superPropertyName);
}
/**
* Register super properties for events, only if no other super property with the
* same names has already been registered.
*
* <p>Calling registerSuperPropertiesOnce will never overwrite existing properties.
*
* @param superProperties A Map containing the super properties to register.
*
* See also {@link #registerSuperPropertiesOnce(org.json.JSONObject)}
*/
public void registerSuperPropertiesOnceMap(Map<String, Object> superProperties) {
if (hasOptedOutTracking()) return;
if (null == superProperties) {
MPLog.e(LOGTAG, "registerSuperPropertiesOnceMap does not accept null properties");
return;
}
try {
registerSuperPropertiesOnce(new JSONObject(superProperties));
} catch (NullPointerException e) {
MPLog.w(LOGTAG, "Can't have null keys in the properties of registerSuperPropertiesOnce!");
}
}
/**
* Register super properties for events, only if no other super property with the
* same names has already been registered.
*
* <p>Calling registerSuperPropertiesOnce will never overwrite existing properties.
*
* @param superProperties A JSONObject containing the super properties to register.
* @see #registerSuperProperties(JSONObject)
*/
public void registerSuperPropertiesOnce(JSONObject superProperties) {
if (hasOptedOutTracking()) return;
mPersistentIdentity.registerSuperPropertiesOnce(superProperties);
}
/**
* Erase all currently registered superProperties.
*
* <p>Future tracking calls to Mixpanel will not contain the specific
* superProperties registered before the clearSuperProperties method was called.
*
* <p>To remove a single superProperty, use {@link #unregisterSuperProperty(String)}
*
* @see #registerSuperProperties(JSONObject)
*/
public void clearSuperProperties() {
mPersistentIdentity.clearSuperProperties();
}
/**
* Updates super properties in place. Given a SuperPropertyUpdate object, will
* pass the current values of SuperProperties to that update and replace all
* results with the return value of the update. Updates are synchronized on
* the underlying super properties store, so they are guaranteed to be thread safe
* (but long running updates may slow down your tracking.)
*
* @param update A function from one set of super properties to another. The update should not return null.
*/
public void updateSuperProperties(SuperPropertyUpdate update) {
if (hasOptedOutTracking()) return;
mPersistentIdentity.updateSuperProperties(update);
}
/**
* Set the group this user belongs to.
*
* @param groupKey The property name associated with this group type (must already have been set up).
* @param groupID The group the user belongs to.
*/
public void setGroup(String groupKey, Object groupID) {
if (hasOptedOutTracking()) return;
List<Object> groupIDs = new ArrayList<>(1);
groupIDs.add(groupID);
setGroup(groupKey, groupIDs);