Skip to content

Commit 2f0efd0

Browse files
committed
initial draft of adding Kotlin examples to android docs
1 parent b7b8401 commit 2f0efd0

File tree

1 file changed

+202
-3
lines changed
  • src/connections/sources/catalog/libraries/mobile/android

1 file changed

+202
-3
lines changed

src/connections/sources/catalog/libraries/mobile/android/index.md

Lines changed: 202 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,17 @@ Analytics analytics = new Analytics.Builder(context, YOUR_WRITE_KEY)
9696
Analytics.setSingletonInstance(analytics);
9797
```
9898

99+
```kotlin
100+
// Create an analytics client with the given context and Segment write key.
101+
val analytics = Analytics.Builder(context, YOUR_WRITE_KEY)
102+
.trackApplicationLifecycleEvents() // Enable this to record certain application events automatically!
103+
.recordScreenViews() // Enable this to record screen views automatically!
104+
.build()
105+
106+
// Set the initialized instance as a globally accessible instance.
107+
Analytics.setSingletonInstance(analytics);
108+
```
109+
99110
**Notes**:
100111
- You can automatically track lifecycle events such as `Application Opened`, `Application Installed`, `Application Updated` to start quickly with core events. These are optional, but highly recommended.
101112
- This only installs the Segment destination. This means that all your data is sent server-side to tools. To bundle additional destinations client-side, you'll need to take some additional steps as [shown here](/docs/connections/sources/catalog/libraries/mobile/android/#packaging-sdks-for-device-mode-destinations).
@@ -108,6 +119,10 @@ The entry point of the library is through the `Analytics` class. As you might ha
108119
Analytics analytics = new Analytics.Builder(context, writeKey).build();
109120
```
110121

122+
```kotlin
123+
val analytics = Analytics.Builder(context, writeKey).build()
124+
```
125+
111126
The `Analytics.Builder` class lets you customize settings for the Analytics client, including things like the flush interval and packaging Device-mode destinations. Refer to the Javadocs for details on customizable parameters.
112127

113128
We also maintain a global default instance which is initialized with defaults suitable to most implementations.
@@ -118,6 +133,12 @@ Analytics.setSingletonInstance(analytics);
118133
Analytics.with(context).track(...);
119134
```
120135

136+
```kotlin
137+
// You can also register your custom instance as a global singleton.
138+
Analytics.setSingletonInstance(analytics)
139+
Analytics.with(context).track(...)
140+
```
141+
121142
In general, Segment recommends that you use the Builder method because it provides the most flexibility. Remember you can call `Analytics.setSingletonInstance` only _ONCE_, so it's best to put the initialization code inside your custom Application class.
122143

123144
```java
@@ -132,6 +153,18 @@ public class MyApp extends Application {
132153
}
133154
```
134155

156+
```kotlin
157+
class MyApp : Application() {
158+
override fun onCreate() {
159+
val analytics = Analytics.Builder(context, writeKey).build()
160+
Analytics.setSingletonInstance(analytics)
161+
162+
// Safely call Analytics.with(context) from anywhere within your app!
163+
Analytics.with(context).track("Application Started")
164+
}
165+
}
166+
```
167+
135168
Once you initialize an Analytics client, you can safely call any of its tracking methods from any thread. These events are dispatched asynchronously to the Segment servers and to any Device-mode destinations.
136169

137170
> warning ""
@@ -168,6 +201,10 @@ Example `identify` call:
168201
```java
169202
Analytics.with(context).identify("a user's id", new Traits().putName("John Doe"), null);
170203
```
204+
205+
```kotlin
206+
Analytics.with(context).identify("a user's id", Traits().putName("John Doe"), null)
207+
```
171208
Segment recommends that you make an Identify call once when the user's first creates an account, and only using the Identify call later when their traits change. Segment remembers the previous userIDs and merges the new traits with the old ones.
172209

173210

@@ -179,6 +216,14 @@ Analytics.with(context).identify(new Traits().putName("Michael Bolton"));
179216
Analytics.with(context).identify(new Traits().putEmail("[email protected]"));
180217
```
181218

219+
```kotlin
220+
// Initially when you only know the user's name
221+
Analytics.with(context).identify(Traits().putName("Michael Bolton"))
222+
223+
// Sometime later in your app when the user gives you their email
224+
Analytics.with(context).identify(Traits().putEmail("[email protected]"))
225+
```
226+
182227
Remember, you can replace the properties and traits in the code samples with variables that represent the data you actually collected.
183228

184229
The Identify call has the following fields:
@@ -219,6 +264,15 @@ Analytics.with(context).track("Product Viewed", new Properties().putValue("name"
219264

220265
```
221266

267+
```kotlin
268+
val analytics = Analytics.Builder(context, writeKey)
269+
.trackApplicationLifecycleEvents()
270+
.build()
271+
272+
Analytics.with(context).track("Product Viewed", Properties().putValue("name", "Moto 360"))
273+
274+
```
275+
222276
This example Track call tells us that your user just triggered the **Product Viewed** event with a name of "Moto 360."
223277

224278
The Track call properties can be anything you want to record, for example:
@@ -227,6 +281,10 @@ The Track call properties can be anything you want to record, for example:
227281
Analytics.with(context).track("Purchased Item", new Properties().putValue("sku", "13d31").putRevenue(199.99));
228282
```
229283

284+
```kotlin
285+
Analytics.with(context).track("Purchased Item", Properties().putValue("sku", "13d31").putRevenue(199.99))
286+
```
287+
230288
The Track call includes the following fields:
231289

232290
<table>
@@ -266,6 +324,17 @@ Analytics.with(context).screen(null, "Photo Feed", new Properties().putValue("Fe
266324
Analytics.with(context).screen("Smartwatches", "Purchase Screen", new Properties().putValue("sku", "13d31"));
267325
```
268326

327+
```kotlin
328+
// category "Feed" and a property "Feed Length"
329+
Analytics.with(context).screen("Feed", Properties().putValue("Feed Length", "26"))
330+
331+
// no category, name "Photo Feed" and a property "Feed Length"
332+
Analytics.with(context).screen(null, "Photo Feed", Properties().putValue("Feed Length", "26"))
333+
334+
// category "Smartwatches", name "Purchase Screen", and a property "sku"
335+
Analytics.with(context).screen("Smartwatches", "Purchase Screen", Properties().putValue("sku", "13d31"))
336+
```
337+
269338
The `screen` call has the following fields:
270339

271340
<table class="api-table">
@@ -300,6 +369,12 @@ Analytics analytics = new Analytics.Builder(context, writeKey)
300369
.build();
301370
```
302371

372+
```kotlin
373+
val analytics = Analytics.Builder(context, writeKey)
374+
.recordScreenViews()
375+
.build()
376+
```
377+
303378
### Group
304379

305380
Group calls let you associate an [identified user](/docs/connections/sources/catalog/libraries/server/java/#identify) user with a group. A group could be a company, organization, account, project or team! It also lets you record custom traits about the group, like industry or number of employees.
@@ -312,6 +387,10 @@ Example `group` call:
312387
Analytics.with(context).group("a user's id", "a group id", new Traits().putEmployees(20));
313388
```
314389

390+
```kotlin
391+
Analytics.with(context).group("a user's id", "a group id", Traits().putEmployees(20))
392+
```
393+
315394
The `group` call has the following fields:
316395

317396
<table class="api-table">
@@ -344,10 +423,15 @@ Alias is how you associate one identity with another. This is an advanced method
344423
Example `alias` call:
345424

346425
```java
347-
Analytics.with(context).alias(newId)
426+
Analytics.with(context).alias(newId);
348427
Analytics.with(context).identify(newId);
349428
```
350429

430+
```kotlin
431+
Analytics.with(context).alias(newId)
432+
Analytics.with(context).identify(newId)
433+
```
434+
351435
The `alias` call has the following fields:
352436

353437
<table class="api-table">
@@ -374,6 +458,11 @@ AnalyticsContext analyticsContext = Analytics.with(context).getAnalyticsContext(
374458
analyticsContext.putValue(...).putReferrer(...).putCampaign(...);
375459
```
376460

461+
```kotlin
462+
val analyticsContext = Analytics.with(context).getAnalyticsContext()
463+
analyticsContext.putValue(...).putReferrer(...).putCampaign(...)
464+
```
465+
377466
You can read more about these special fields in the [Segment Common spec documentation](/docs/connections/spec/common/#context).
378467

379468
To alter data specific to the device object you can use the following:
@@ -383,6 +472,11 @@ AnalyticsContext analyticsContext = Analytics.with(context).getAnalyticsContext(
383472
analyticsContext.device().putValue("advertisingId", "1");
384473
```
385474

475+
```kotlin
476+
val analyticsContext = Analytics.with(context).getAnalyticsContext()
477+
analyticsContext.device().putValue("advertisingId", "1")
478+
```
479+
386480
To opt out of automatic data collection, clear the context after initializing the client. Do this _BEFORE_ you send any events.
387481

388482
```java
@@ -391,6 +485,12 @@ AnalyticsContext context = analytics.getContext();
391485
context.clear();
392486
```
393487

488+
```kotlin
489+
val analytics = Analytics.Builder(context, writeKey).defaultOptions(defaultOptions).build()
490+
val context = analytics.getContext()
491+
context.clear()
492+
```
493+
394494
## Routing collected data
395495

396496
Once you set up calls using the basic Segment data collection APIs, choose which destinations to send it to, and how you want to send it to them.
@@ -435,6 +535,14 @@ Analytics analytics = new Analytics.Builder(context, writeKey)
435535
.build();
436536
```
437537

538+
```kotlin
539+
val analytics = Analytics.Builder(context, writeKey)
540+
.use(GoogleAnalyticsIntegration.FACTORY)
541+
.use(BranchIntegration.FACTORY)
542+
...
543+
.build()
544+
```
545+
438546
### Selecting Destinations
439547

440548
You can pass an `options` object on any of the basic Segment API calls that allows you to turn specific destinations on or off. By default, all destinations are enabled. (In Segment's other libraries, you could do this in the list of `integrations` inside the `options` object.)
@@ -452,6 +560,17 @@ Analytics.with(context).track("Purchased Item", new Properties(), new Options().
452560
Analytics.with(context).track("Purchased Item", new Properties(), new Options().setIntegration(Options.ALL_INTEGRATIONS_KEY, false).setIntegration("Countly", true).setIntegration("Google Analytics", true));
453561
```
454562

563+
```kotlin
564+
// Sent to all destinations
565+
Analytics.with(context).track("Viewed Item", Properties())
566+
567+
// Sent to all destinations, except Mixpanel
568+
Analytics.with(context).track("Purchased Item", Properties(), Options().setIntegration("Mixpanel", false))
569+
570+
// Sent only to Google Analytics and Countly
571+
Analytics.with(context).track("Purchased Item", Properties(), Options().setIntegration(Options.ALL_INTEGRATIONS_KEY, false).setIntegration("Countly", true).setIntegration("Google Analytics", true))
572+
```
573+
455574
If you build your own instance of the client, you can also specify a default `options` object to use for each call. In the example below, _NONE_ of the analytics events are sent to Heap.
456575

457576
```java
@@ -467,6 +586,19 @@ Analytics.setSingletonInstance(analytics);
467586
Analytics.with(context).track("Viewed Item", new Properties());
468587
```
469588

589+
```kotlin
590+
// Disable Heap destination
591+
val defaultOptions = Options().setIntegration("Heap", false)
592+
593+
// Attach the options to our client
594+
val analytics = Analytics.Builder(context, writeKey).defaultOptions(defaultOptions).build()
595+
// Set the client as a global singleton so it can be called from anywhere
596+
Analytics.setSingletonInstance(analytics)
597+
598+
// Now any calls made with this Analytics client won't be sent to Heap
599+
Analytics.with(context).track("Viewed Item", Properties())
600+
```
601+
470602
Notice that the first example uses an Enum to disable the destination, but the second example uses a String. Segment recommends that you use the Enum method for Device-mode destinations, and use the String method to change the behavior of Cloud-mode destinations. The Enum method ensures type safety, and prevents you from accidentally disabling "GoogleAnalytics" instead of "Google Analytics", while the String method gives you more flexibility in what options you pass to cloud-mode destinations.
471603

472604
Destination name flags are **case sensitive** and match [the destination's name in the docs](/docs/connections/destinations/catalog/) In some cases where a destination's name has more than one spelling (for example if it changed names, or brand capitalization styles, or if it was commonly misspelled and we added an alias) the documentation for that destination will include a section called "Adding (destination name) to the integrations object".
@@ -483,7 +615,7 @@ Destination name flags are **case sensitive** and match [the destination's name
483615
You can retrieve the `anonymousId` set by the library by using:
484616

485617
```java
486-
Analytics.with(context).getAnalyticsContext().traits().anonymousId()
618+
Analytics.with(context).getAnalyticsContext().traits().anonymousId();
487619
```
488620

489621
### Reset
@@ -492,7 +624,7 @@ The `reset` method clears the SDK's internal stores for the current user and gro
492624

493625
The example code below clears all information about the user.
494626
```java
495-
Analytics.with(context).reset()
627+
Analytics.with(context).reset();
496628
```
497629

498630
Events queued on disk are _not_ cleared and are uploaded the next time the app starts.
@@ -511,6 +643,12 @@ log(snapshot.integrationOperationAverageDuration);
511643
log(snapshot.flushCount);
512644
```
513645

646+
```kotlin
647+
val snapshot = Analytics.with(context).getSnapshot()
648+
log(snapshot.integrationOperationAverageDuration)
649+
log(snapshot.flushCount)
650+
```
651+
514652
### Adding debug logging
515653

516654
If you run into issues while using the Android library, you can enable logging to help trace the issue. Logging also helps you see how long destinations take to complete their calls so you can find performance bottlenecks.
@@ -521,6 +659,10 @@ The logging is enabled by default in the default singleton instance if your appl
521659
Analytics analytics = new Analytics.Builder(context, writeKey).logLevel(LogLevel.VERBOSE)...build();
522660
```
523661

662+
```kotlin
663+
val analytics = Analytics.Builder(context, writeKey).logLevel(LogLevel.VERBOSE)...build()
664+
```
665+
524666
You can choose to disable logging completely (`LogLevel.NONE`), enable basic logging for the SDK (`LogLevel.BASIC`), enable basic logging for Device-mode destination (`LogLevel.INFO`), or simply log everything (`LogLevel.VERBOSE`).
525667

526668
> success ""
@@ -539,6 +681,12 @@ public void optOut(boolean optOut) {
539681
}
540682
```
541683

684+
```kotlin
685+
fun optOut(optOut: boolean) {
686+
this.optOut.set(optOut)
687+
}
688+
```
689+
542690
Set the opt-out status for the current device and analytics client combination. This flag
543691
persists across device reboots, so you can call it once in your application,
544692
such as in a screen where a user can opt out of analytics tracking.
@@ -579,6 +727,36 @@ properties.putProducts(product1, product2);
579727
Analytics.with(context).track("Order Completed", properties);
580728
```
581729

730+
```kotlin
731+
import com.segment.analytics.Analytics
732+
import com.segment.analytics.Properties
733+
import com.segment.analytics.Properties.Product
734+
735+
// initialize product variables
736+
lateinit var id: String
737+
lateinit var orderId: String
738+
lateinit var sku: String
739+
var price = 0.0
740+
var revenue = 0.0
741+
// initialize a new properties object
742+
val properties = Properties();
743+
744+
// add orderId and revenue to the properties object
745+
properties.putValue("orderId", orderId).putValue("revenue", revenue)
746+
747+
// initialize a new product
748+
Product product1 = new Product(id, sku, price)
749+
750+
// initialize a second product
751+
Product product2 = new Product(id, sku, price)
752+
753+
// add products to the properties object
754+
properties.putProducts(product1, product2)
755+
756+
// pass the properties object into your Order Completed event
757+
Analytics.with(context).track("Order Completed", properties)
758+
```
759+
582760
Find details on **best practices in event naming** as well as the **Track method payload** in the [Segment Track call spec](/docs/connections/spec/track/).
583761

584762

@@ -598,6 +776,19 @@ Analytics analytics = new Analytics.Builder(this, ANALYTICS_WRITE_KEY) //
598776
.build();
599777
```
600778

779+
```kotlin
780+
val analytics = Analytics.Builder(this, ANALYTICS_WRITE_KEY) //
781+
.connectionFactory(object: ConnectionFactory() {
782+
@Throws(IOException::class)
783+
override fun openConnection(url: String): HttpURLConnection {
784+
val path = Uri.parse(url).path
785+
// Replace YOUR_PROXY_HOST with the address of your proxy, e.g. https://aba64da6.ngrok.io.
786+
return super.openConnection("YOUR_PROXY_HOST$path")
787+
}
788+
})
789+
.build()
790+
```
791+
601792

602793
## Analytics-Android Versions
603794

@@ -725,3 +916,11 @@ Analytics analytics = new Analytics.Builder(context, writeKey)
725916
...
726917
.build();
727918
```
919+
920+
```kotlin
921+
val analytics = Analytics.Builder(context, writeKey)
922+
.use(GoogleAnalyticsIntegration.FACTORY)
923+
.use(BranchIntegration.FACTORY)
924+
...
925+
.build()
926+
```

0 commit comments

Comments
 (0)