Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add Kotlin android sample #23

Merged
merged 5 commits into from
Apr 5, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,10 @@ class AndroidStorage(
}

override fun getEventCallback(insertId: String): EventCallBack? {
return eventCallbacksMap.getOrDefault(insertId, null)
if (eventCallbacksMap.contains(insertId)) {
return eventCallbacksMap.get(insertId)
}
return null
}

override fun removeEventCallback(insertId: String) {
Expand Down
62 changes: 47 additions & 15 deletions core/src/main/java/com/amplitude/core/Amplitude.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ import kotlinx.coroutines.launch
import org.json.JSONObject
import java.util.concurrent.Executors

/**
* <h1>Amplitude</h1>
* This is the SDK instance class that contains all of the SDK functionality.<br><br>
* Many of the SDK functions return the SDK instance back, allowing you to chain multiple method calls together
qingzhuozhen marked this conversation as resolved.
Show resolved Hide resolved
qingzhuozhen marked this conversation as resolved.
Show resolved Hide resolved
*/
open class Amplitude internal constructor(
val configuration: Configuration,
val store: State,
Expand Down Expand Up @@ -68,104 +73,131 @@ open class Amplitude internal constructor(
}

@Deprecated("Please use 'track' instead.", ReplaceWith("track"))
fun logEvent(event: BaseEvent) {
track(event)
fun logEvent(event: BaseEvent): Amplitude {
return track(event)
}

fun track(event: BaseEvent, callback: EventCallBack? = null) {
/**
* Track an event
qingzhuozhen marked this conversation as resolved.
Show resolved Hide resolved
*/
fun track(event: BaseEvent, callback: EventCallBack? = null): Amplitude {
callback ?. let {
event.callback = it
}
process(event)
return this
}

fun track(eventType: String, eventProperties: JSONObject? = null, options: EventOptions? = null) {
/**
* Log event with the specified event type, event properties, and optional event options
qingzhuozhen marked this conversation as resolved.
Show resolved Hide resolved
*/
fun track(eventType: String, eventProperties: JSONObject? = null, options: EventOptions? = null): Amplitude {
val event = BaseEvent()
event.eventType = eventType
event.eventProperties = eventProperties
options ?. let {
event.mergeEventOptions(it)
}
process(event)
return this
}

/**
* Identify. Use this to send an Identify object containing user property operations to Amplitude server.
qingzhuozhen marked this conversation as resolved.
Show resolved Hide resolved
*/
fun identify(identify: Identify, options: EventOptions? = null) {
fun identify(identify: Identify, options: EventOptions? = null): Amplitude {
val event = IdentifyEvent()
event.userProperties = identify.properties
options ?. let {
event.mergeEventOptions(it)
}
process(event)
return this
}

fun identify(userId: String) {
/**
* Sets the user id (can be null).
*/
fun setUserId(userId: String?): Amplitude {
this.idContainer.identityManager.editIdentity().setUserId(userId).commit()
return this
}

fun setDeviceId(deviceId: String) {
/**
* Sets a custom device id. <b>Note: only do this if you know what you are doing!</b>
*/
fun setDeviceId(deviceId: String): Amplitude {
this.idContainer.identityManager.editIdentity().setDeviceId(deviceId).commit()
return this
}

fun groupIdentify(groupType: String, groupName: String, identify: Identify, options: EventOptions? = null) {
/**
* Identify a group
*/
fun groupIdentify(groupType: String, groupName: String, identify: Identify, options: EventOptions? = null): Amplitude {
val event = GroupIdentifyEvent()
var group: JSONObject? = null
try {
group = JSONObject().put(groupType, groupName)
} catch (e: Exception) {
logger.error(e.toString())
logger.error("Error in groupIdentif: ${e.toString()}")
}
event.groups = group
event.groupProperties = identify.properties
options ?. let {
event.mergeEventOptions(it)
}
process(event)
return this
}

/**
* Sets the user's group.
qingzhuozhen marked this conversation as resolved.
Show resolved Hide resolved
*/
fun setGroup(groupType: String, groupName: String, options: EventOptions? = null) {
fun setGroup(groupType: String, groupName: String, options: EventOptions? = null): Amplitude {
val identify = Identify().set(groupType, groupName)
identify(identify, options)
return this
}

/**
* ets the user's groups.
qingzhuozhen marked this conversation as resolved.
Show resolved Hide resolved
*/
fun setGroup(groupType: String, groupName: Array<String>, options: EventOptions? = null) {
fun setGroup(groupType: String, groupName: Array<String>, options: EventOptions? = null): Amplitude {
val identify = Identify().set(groupType, groupName)
identify(identify, options)
return this
}

@Deprecated("Please use 'revenue' instead.", ReplaceWith("revenue"))
fun logRevenue(revenue: Revenue) {
fun logRevenue(revenue: Revenue): Amplitude {
revenue(revenue)
return this
}

/**
* Create a Revenue object to hold your revenue data and properties,
* and log it as a revenue event using this method.
*/
fun revenue(revenue: Revenue, options: EventOptions? = null) {
fun revenue(revenue: Revenue, options: EventOptions? = null): Amplitude {
if (!revenue.isValid()) {
return
logger.warn("Invalid revenue object, missing required fields")
return this
}
val event = revenue.toRevenueEvent()
options ?. let {
event.mergeEventOptions(it)
}
revenue(event)
return this
}

/**
* Log a Revenue Event
*/
fun revenue(event: RevenueEvent) {
fun revenue(event: RevenueEvent): Amplitude {
process(event)
return this
}

private fun process(event: BaseEvent) {
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/com/amplitude/core/events/Identify.kt
Original file line number Diff line number Diff line change
Expand Up @@ -569,7 +569,7 @@ class Identify() {
properties.getJSONObject(operation.operationType).put(property, value)
propertySet.add(property)
} catch (e: Exception) {
ConsoleLogger.logger.error(e.toString())
ConsoleLogger.logger.error("Error in set uset property: ${e.toString()}")
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ class EventPipeline(
storage.writeEvent(message.event)
} catch (e: Exception) {
e.message?.let {
amplitude.logger.error(it)
amplitude.logger.error("Error when write event: $it")
}
}

Expand Down Expand Up @@ -117,7 +117,7 @@ class EventPipeline(
responseHandler?.handle(connection.response)
} catch (e: Exception) {
e.message?.let {
amplitude.logger.error(it)
amplitude.logger.error("Error when upload event: $it")
}
}
}
Expand Down
78 changes: 46 additions & 32 deletions core/src/main/java/com/amplitude/core/utilities/JSONUtil.kt
Original file line number Diff line number Diff line change
Expand Up @@ -157,50 +157,50 @@ internal fun JSONArray.toIntArray(): IntArray {
internal fun JSONObject.toBaseEvent(): BaseEvent {
val event = BaseEvent()
event.eventType = this.getString("event_type")
event.userId = this.optString("user_id", null)
event.deviceId = this.optString("device_id", null)
event.userId = this.optionalString("user_id", null)
event.deviceId = this.optionalString("device_id", null)
event.timestamp = if (this.has("time")) this.getLong("time") else null
event.eventProperties = this.optJSONObject("event_properties", null)
event.userProperties = this.optJSONObject("user_properties", null)
event.groups = this.optJSONObject("groups", null)
event.appVersion = this.optString("app_version", null)
event.platform = this.optString("platform", null)
event.osName = this.optString("os_name", null)
event.osVersion = this.optString("os_version", null)
event.deviceBrand = this.optString("device_brand", null)
event.deviceManufacturer = this.optString("device_manufacturer", null)
event.deviceModel = this.optString("device_model", null)
event.carrier = this.optString("carrier", null)
event.country = this.optString("country", null)
event.region = this.optString("region", null)
event.city = this.optString("city", null)
event.dma = this.optString("dma", null)
event.language = this.optString("language", null)
event.eventProperties = this.optionalJSONObject("event_properties", null)
event.userProperties = this.optionalJSONObject("user_properties", null)
event.groups = this.optionalJSONObject("groups", null)
event.appVersion = this.optionalString("app_version", null)
event.platform = this.optionalString("platform", null)
event.osName = this.optionalString("os_name", null)
event.osVersion = this.optionalString("os_version", null)
event.deviceBrand = this.optionalString("device_brand", null)
event.deviceManufacturer = this.optionalString("device_manufacturer", null)
event.deviceModel = this.optionalString("device_model", null)
event.carrier = this.optionalString("carrier", null)
event.country = this.optionalString("country", null)
event.region = this.optionalString("region", null)
event.city = this.optionalString("city", null)
event.dma = this.optionalString("dma", null)
event.language = this.optionalString("language", null)
event.price = if (this.has("price")) this.getDouble("price") else null
event.quantity = if (this.has("quantity")) this.getInt("quantity") else null
event.revenue = if (this.has("revenue")) this.getDouble("revenue") else null
event.productId = this.optString("productId", null)
event.revenueType = this.optString("revenueType", null)
event.productId = this.optionalString("productId", null)
event.revenueType = this.optionalString("revenueType", null)
event.locationLat = if (this.has("location_lat")) this.getDouble("location_lat") else null
event.locationLng = if (this.has("location_lng")) this.getDouble("location_lng") else null
event.ip = this.optString("ip", null)
event.idfa = this.optString("idfa", null)
event.idfv = this.optString("idfv", null)
event.adid = this.optString("adid", null)
event.androidId = this.optString("android_id", null)
event.ip = this.optionalString("ip", null)
event.idfa = this.optionalString("idfa", null)
event.idfv = this.optionalString("idfv", null)
event.adid = this.optionalString("adid", null)
event.androidId = this.optionalString("android_id", null)
event.eventId = if (this.has("event_id")) this.getInt("event_id") else null
event.sessionId = this.getLong("session_id")
event.insertId = this.optString("insert_id", null)
event.insertId = this.optionalString("insert_id", null)
event.library = if (this.has("library")) this.getString("library") else null
event.partnerId = this.optString("partner_id", null)
event.partnerId = this.optionalString("partner_id", null)
qingzhuozhen marked this conversation as resolved.
Show resolved Hide resolved
event.plan = if (this.has("plan")) Plan.fromJSONObject(this.getJSONObject("plan")) else null
return event
}

internal fun JSONArray.toEvents(): List<BaseEvent> {
val events = mutableListOf<BaseEvent>()
this.forEach {
events.add((it as JSONObject).toBaseEvent())
(0 until this.length()).forEach {
events.add((this.getJSONObject(it)).toBaseEvent())
}
return events
}
Expand All @@ -209,11 +209,11 @@ internal fun JSONArray.split(): Pair<String, String> {
val mid = this.length() / 2
val firstHalf = JSONArray()
val secondHalf = JSONArray()
this.forEachIndexed { index, obj ->
(0 until this.length()).forEach { index, ->
if (index < mid) {
firstHalf.put(obj)
firstHalf.put(this.getJSONObject(index))
} else {
secondHalf.put(obj)
secondHalf.put(this.getJSONObject(index))
}
}
return Pair(firstHalf.toString(), secondHalf.toString())
Expand All @@ -224,3 +224,17 @@ internal fun JSONObject.addValue(key: String, value: Any?) {
this.put(key, value)
}
}

inline fun JSONObject.optionalJSONObject(key: String, defaultValue: JSONObject?): JSONObject?{
if (this.has(key)) {
return this.getJSONObject(key)
}
return defaultValue
}

inline fun JSONObject.optionalString(key: String, defaultValue: String?): String?{
if (this.has(key)) {
return this.getString(key)
}
return defaultValue
}
49 changes: 49 additions & 0 deletions samples/kotlin-android-app/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
plugins {
id 'com.android.application'
id 'kotlin-android'
}
ext {
AMPLITUDE_API_KEY = ""
}

android {
compileSdk 31

defaultConfig {
applicationId "com.amplitude.android.sample"
minSdk 16
targetSdk 31
versionCode 1
versionName "1.0"
multiDexEnabled true
buildConfigField "String", "AMPLITUDE_API_KEY", "\"${AMPLITUDE_API_KEY}\""
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
lintOptions {
abortOnError false
}
}

dependencies {
implementation project(':android')
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
implementation 'com.google.android.gms:play-services-ads:20.6.0'
implementation 'com.google.android.gms:play-services-appset:16.0.2'
}
23 changes: 23 additions & 0 deletions samples/kotlin-android-app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
play-services-ads.-keep class com.google.android.gms.ads.** { *; }

Loading