メインコンテンツまでスキップ

Android SDK+ 統合ガイド

Language
For Rokt Ecommerce partners. This complete guide is for ecommerce businesses integrating Rokt into transaction experiences they own. It is not an advertiser implementation guide. Advertisers should use the Rokt Ads integration guides.

このページでは、Rokt Ecommerce Android SDK+の実装方法について説明します。SDK+は、設定された画面でユーザーとトランザクションデータをRoktに渡し、Roktが確認画面などで関連するエクスペリエンスを表示できるようにします。

1. Add the Rokt SDK+ to Your Android App#

Rokt SDK+は、最低Android APIレベル21+(Android 5.0 Lollipop)が必要です。

必要な依存関係を含めるためにGradleファイルを更新してください:

build.gradle.kts dependencies
dependencies {
implementation("com.mparticle:android-rokt-kit:6.0.0")
implementation("com.mparticle:android-core:6.0.0")
}
build.gradle dependencies
dependencies {
implementation "com.mparticle:android-rokt-kit:6.0.0"
implementation "com.mparticle:android-core:6.0.0"
}

2. Initialize the Rokt SDK+#

次の初期化スニペットを、onCreate()クラスのApplicationメソッドに挿入します。SDK+は、他のSDK+ API呼び出しの前に初期化される必要があります。your-keyyour-secretを、Roktチームから提供されたキーとシークレットに置き換えてください。

Application.onCreate initialization
import com.mparticle.MParticle
import com.mparticle.MParticleOptions
import com.mparticle.networking.NetworkOptions

class YourApplicationClass : Application() {
override fun onCreate() {
super.onCreate()

// Identify the current user:
// If you do not have the user's email address, you can pass in a null value
val identifyRequest = IdentityApiRequest.withEmptyUser()
// Preferred: pass the customer's raw, unhashed email via .email().
// If you can only provide a SHA-256-hashed email, remove .email() and use .userIdentity(Other) instead — do not pass both.
.email("j.smith@example.com")
.userIdentity(MParticle.IdentityType.Other, "SHA-256 hashed email") // only if raw email unavailable
// If you can only provide a SHA-256-hashed mobile number, use 'other2' instead of MobileNumber — do not pass both.
.userIdentity(MParticle.IdentityType.Other2, "SHA-256 hashed mobile number") // only if raw mobile unavailable
// Customer phone number in E.164 format.
.userIdentity(MParticle.IdentityType.MobileNumber, "+13125551515")
// Partner's internal customer/account identifier (if the user is logged in).
.customerId("cust_10482")
.build()

// If the user is identified with their email address, set additional user attributes.
val identifyTask = BaseIdentityTask()
.addSuccessListener { identityApiResult ->
val user = identityApiResult.user
user.setUserAttribute("example attribute key", "example attribute value")
}

// Enter your custom subdomain if you are using a first-party domain configuration (optional)
val networkOptions = NetworkOptions.builder()
.setCustomBaseURL("https://rkt.example.com")
.build()

val options: MParticleOptions = MParticleOptions.builder(this)
.credentials(
"your-key", // The key provided by your Rokt account manager
"your-secret" // The secret provided by your Rokt account manager
)
// Specify the data environment with environment:
// Set it to Development if you are still testing your integration.
// Set it to Production if your integration is ready for production data.
// The default is AutoDetect which attempts to detect the environment automatically.
.environment(MParticle.Environment.Development)
.networkOptions(networkOptions)
.identify(identifyRequest)
.identifyTask(identifyTask)
.build()

MParticle.start(options)
}
}

Applicationクラスに初期化スニペットを挿入すると、次のカスタマイズ可能なフィールドが表示されます:

1Entering your Rokt key and secret#

your-key内のyour-secretcredentialsを、Roktアカウントマネージャーから提供されたキーとシークレットの値に設定します。

2Setting your data environment#

テスト中は、environmentMParticle.Environment.Developmentに設定してデータを開発環境にルーティングし、ライブ顧客活動を本番環境に送信するにはMParticle.Environment.Productionに設定します。

3Entering a custom first-party domain#

First-Party Domain Configurationの指示に従い、customBaseURLNetworkOptionsに設定してカスタムサブドメインを指定します。Rokt SDK+を独自のドメイン経由でルーティングすることで、広告ブロッカーやブラウザによる広告やデータのブロックのリスクを軽減できます。networkOptionsを省略すると、Roktのデフォルトエンドポイントにトラフィックが送信されます。

4Identifying your user and setting attributes#

identifyRequestで、ユーザーの生のハッシュされていないメールを.email()を通じて渡します。ハッシュされたメールやその他の識別子については、Supported User Identifiersを参照してください。識別された後、identifyTaskの成功リスナーを使用して追加のユーザー属性を設定します。推奨されるリストについてはUser Attributesを参照してください。

identifyTask success listener
val identifyTask = BaseIdentityTask()
.addSuccessListener { identityApiResult ->
val user = identityApiResult.user
user.setUserAttribute("example attribute key", "example attribute value")
}
注記

初期化スニペットには必ずidentifyRequestを含めてください。初期化時にユーザーのメールがない場合は、.email()呼び出しを省略してください。SDK+は依然として初期化され、後で3. Identify the Userを通じてユーザーを識別できます。addFailureListenerコールバックの処理方法については、Error Handlingを参照してください。エラーハンドリングがないと、大規模なデータの一貫性の問題が発生する可能性があります。

Initializing with fontsInitializing with fonts への直接リンク

One Platformでフォントを提供する代わりに、またはそれに加えて、アプリケーションに既にバンドルされているフォントを使用することができます。これにより、初期化時にフォントがダウンロードされる可能性がなくなり、ネットワークの利用が削減され、ダウンロードエラーの可能性が減少します。

フォントアセットの使用フォントアセットの使用 への直接リンク

フォントのPostScript名をroktOptionsビルダーメソッドにマップし、assetsディレクトリ内のファイルパスにマップします。レイアウトで使用されているPostScript名が不明な場合は、アカウントマネージャーに確認してください。

Font assets
import com.mparticle.MParticle
import com.mparticle.MParticleOptions

class YourApplication : Application() {
override fun onCreate() {
super.onCreate()
val options: MParticleOptions = MParticleOptions.builder(this)
.credentials("your-key", "your-secret")
.environment(MParticle.Environment.Development)
.roktOptions(RoktOptions(fontFilePathMap = mapOf("Arial-Bold" to "fonts/arialbold.otf")))
.build()
MParticle.start(options)
}
}

3. Identify the User#

SDK+ 初期化スクリプトは、スクリプトのidentifyRequestオブジェクトで提供された識別子を使用して現在のユーザーを識別します。SDKの初期化後、ユーザーがログイン、ログアウト、または識別子を提供するたびに(例えば、チェックアウト時)、以下に説明する適切な方法を使用してユーザーの識別情報を同期させ続ける必要があります。

サポートされているユーザー識別子サポートされているユーザー識別子 への直接リンク

サポートされているユーザー識別子を表示
フィールド説明
emailstring顧客の生のハッシュされていないメールアドレスを .email("j.smith@example.com") を介して渡します。
mobilestring顧客の電話番号を E.164 形式で .userIdentity(MParticle.IdentityType.MobileNumber, "+13125551515") を介して渡します。
customeridstring内部の顧客/アカウント識別子を .customerId("cust_10482") を介して渡します。ログインしているユーザーにはすべての画面で送信してください。
otherstringSHA-256 ハッシュされたメールを .userIdentity(MParticle.IdentityType.Other, "hashed email") を介して渡します。生のメールを提供できない場合にのみ使用してください。
other2stringSHA-256 ハッシュされた携帯番号を .userIdentity(MParticle.IdentityType.Other2, "hashed mobile") を介して渡します。

ユーザーを識別するには:

1Create an identifyRequest object#

ユーザーの識別子を含む identifyRequest オブジェクトを作成します。ユーザーの生のハッシュされていないメールアドレスを email フィールドに統合する必要があります。

2Create an identityCallback#

追加のユーザー属性を設定するには、identityCallback を作成します。identifyRequest が成功した場合、コールバック内で設定したユーザー属性は識別されたユーザーに割り当てられます。

3Send the request using the method that matches the user's action#

ユーザーのアクションに一致するメソッドに identifyRequest(およびオプションの identityCallback)を渡します:

  • MParticle.getInstance()?.Identity()?.login: ユーザーがログインまたはアカウントを作成したときに呼び出します。
  • MParticle.getInstance()?.Identity()?.identify: ログイン遷移なしでセッション中にユーザーのメールを取得したときに呼び出します(例:ゲストがチェックアウト時にメールを入力した場合)。
  • MParticle.getInstance()?.Identity()?.logout: ユーザーがログアウトしたときに呼び出します。

これらのメソッドを呼び出すと、SDK の現在のユーザーの状態の記録が移行されます。login および logout メソッドは、Rokt のアトリビューションを改善するために対応するイベントを自動的にログに記録します。

例えば、Jane Smith という名前のユーザーをメールアドレス j.smith@example.com、携帯番号 +13125551515、顧客 ID cust_10482 で識別するには:

Identify Jane Smith
// 1. Create the identifyRequest object
val identifyRequest = IdentityApiRequest.withEmptyUser()
// Preferred: pass the customer's raw, unhashed email via .email().
// If you can only provide a SHA-256-hashed email, remove .email() and use .userIdentity(Other) instead — do not pass both.
.email("j.smith@example.com")
.userIdentity(MParticle.IdentityType.Other, "SHA-256 hashed email") // only if raw email unavailable
// If you can only provide a SHA-256-hashed mobile number, use 'other2' instead of MobileNumber — do not pass both.
.userIdentity(MParticle.IdentityType.Other2, "SHA-256 hashed mobile number") // only if raw mobile unavailable
.userIdentity(MParticle.IdentityType.MobileNumber, "+13125551515")
.customerId("cust_10482")
.build()

// 2. Optionally set user attributes once the request succeeds.
val identityCallback = BaseIdentityTask()
.addSuccessListener { identityApiResult ->
val user = identityApiResult.user
user.setUserAttribute("firstname", "Jane")
user.setUserAttribute("lastname", "Smith")
}

// 3. Call one of the following methods that best matches the user's action:
MParticle.getInstance()?.Identity()?.login(identifyRequest, identityCallback) // Call when the user logs in or creates an account
MParticle.getInstance()?.Identity()?.identify(identifyRequest, identityCallback) // Call when you obtain the user's email mid-session, but not during a login
MParticle.getInstance()?.Identity()?.logout() // Call when the user logs out

4. Set User Attributes#

ユーザーがアプリをナビゲートする際に、段階的にユーザー属性を設定してください。チェックアウト時だけではありません。設定する属性が多いほど、Rokt は顧客を解決し、関連するオファーを提供するのに役立ちます。

Set User Attributes
import com.mparticle.MParticle

// Retrieve the current user. This will only succeed if you have identified the user during SDK+ initialization or by calling the identify method.
val currentUser = MParticle.getInstance()?.Identity()?.currentUser

// Once you have successfully set the current user to `currentUser`, you can set user attributes with:
currentUser?.setUserAttribute("custom-attribute-name", "custom-attribute-value")
// Note: all user attributes (including list attributes and tags) must have distinct names.

// Rokt recommends setting as many of the following user attributes as possible:
currentUser?.setUserAttribute("firstname", "John")
currentUser?.setUserAttribute("lastname", "Doe")
// Phone numbers can be formatted either as '1234567890', or '+1 (234) 567-8901'
currentUser?.setUserAttribute("mobile", "3125551515")
currentUser?.setUserAttribute("age", "33")
currentUser?.setUserAttribute("gender", "M")
currentUser?.setUserAttribute("billingcity", "Brooklyn")
currentUser?.setUserAttribute("billingstate", "NY")
currentUser?.setUserAttribute("billingzipcode", "123456")
currentUser?.setUserAttribute("dob", "yyyymmdd")
currentUser?.setUserAttribute("title", "Mr")
currentUser?.setUserAttribute("language", "en")
currentUser?.setUserAttribute("predictedltv", "136.23")

// You can create a user attribute to contain a list of values
currentUser?.setUserAttributeList("favorite-genres", listOf("documentary", "comedy", "romance", "drama"))

// To remove a user attribute, call removeUserAttribute and pass in the attribute name. All user attributes share the same key space.
currentUser?.removeUserAttribute("attribute-to-remove")

ユーザー属性ユーザー属性 への直接リンク

収集可能な限り、以下の項目を設定してください:

すべてのユーザー属性を表示
フィールドタイプ説明
firstnamestring顧客の名。パーソナライズに使用されます。
lastnamestring顧客の姓。パーソナライズに使用されます。
mobilestring電話番号は 1112345678 または +1 (222) 345-6789 の形式で。アイデンティティ解決と関連性に使用されます。
birthyearinteger顧客の出生年(例: 1990)。推奨される生年月日フィールド。代替: dob, age。適格性と関連性に使用されます。
ageinteger顧客の年齢。dob の代替。適格性と関連性に使用されます。
dobstring生年月日、yyyymmddage の代替。適格性と関連性に使用されます。
genderstring顧客の性別。例: M, F, Male, または Female。関連性に使用されます。
titlestring敬称。例: Mr, Mrs, Ms。パーソナライズに使用されます。
languagestring購入に関連するISO 639-1言語コード。関連性に使用されます。
billingaddress1string住所(例: 123 Main St)。アイデンティティ解決と関連性に使用されます。
billingaddress2stringアパート/ユニット(例: Apt 4B)。アイデンティティ解決に使用されます。
billingcitystring請求先都市。関連性に使用されます。
billingstatestring請求先州/省/地域。関連性と適格性に使用されます。
billingzipcodestring完全なZIPまたは郵便番号(米国の優先はZIP+4)。アイデンティティ解決と関連性に使用されます。
countrystringISO 3166-1 alpha-2国コード(例: US, GB, AU)。適格性と関連性に使用されます。
newcustomerboolean初回購入者かどうか。関連性に使用されます。
customertypestringユーザーが認証されているかどうか(guest / logged_in)。関連性に使用されます。
loyaltytierstringパートナーのロイヤルティプログラムの階層。関連性と適格性に使用されます。
loyaltyidstringロイヤルティプログラムのメンバーID。アイデンティティ解決に使用されます。
predictedltvdecimal予測される生涯価値(通常はパートナーのMLモデルから)。関連性に使用されます。
subscriptionstatusstring該当する場合のサブスクリプション状態 (active, trial, churned, paused, none)。関連性と適格性に使用されます。
customersegmentstringパートナー内部のセグメンテーション(例: vip, at_risk, new, reactivated)。関連性に使用されます。
acquisitionchannelstring顧客が最初に取得された方法。関連性に使用されます。

すべてのユーザー属性(リスト属性を含む)は、異なる名前を持たなければなりません。

5. Log Events#

Roktが各顧客がどの段階にいるかを理解できるように、画面ビュー、コマースイベント、およびカスタムイベントを追跡します。

Event category

画面の名前(例: "homepage", "product_detail_page")を指定して、MParticle.getInstance()?.logScreen()を呼び出します。追加のカスタム属性を情報マップに含めます。

Log a screen view
MParticle.getInstance()?.logScreen(
"homepage",
mapOf("custom-attribute" to "custom-value")
)

6. Show a Placement#

すべての支払いおよび確認画面でselectPlacementsを呼び出し、Roktがコンテンツをレンダリングするようにします。画面タイプとテストまたは本番用であるかを指定するために、次のページ識別子のいずれかを含めます。

  • stg.rokt.conf: A confirmation screen in a staging (or testing) environment.
  • prod.rokt.conf: A confirmation screen in a production environment.
  • stg.rokt.payments: A payments screen in a staging (or testing) environment.
  • prod.rokt.payments: A payments screen in a production environment.

配置属性配置属性 への直接リンク

これらの属性は、attributes マップ内の selectPlacements に渡します。常に最新の値を提供してください。ここで渡された属性は、以前の setUserAttribute 呼び出しを上書きします。

すべての配置属性を表示
フィールドタイプ説明
emailstring顧客のメールアドレス(ハッシュ化されていない)。アイデンティティ解決に使用されます。
firstnamestring顧客の名前。パーソナライズに使用されます。
lastnamestring顧客の姓。パーソナライズに使用されます。
mobilestringE.164形式の顧客の携帯電話番号。アイデンティティ解決に使用されます。
confirmationrefstring注文/確認参照番号。関連性と重複排除に使用されます。
currencystringトランザクション通貨(ISO 4217、例: USD, GBP, AUD)。関連性に使用されます。
countrystringISO 3166-1 alpha-2 国コード。適格性と関連性に使用されます。
languagestring顧客の希望言語(ISO 639-1)。関連性に使用されます。
totalpricedecimal税金と送料を含むカートの合計値。関連性に使用されます。
amountdecimal税金と送料を除いたカートの小計。totalprice とは異なります。関連性に使用されます。
cartItemsarrayカートラインオブジェクトの構造化された配列。キャメルケースである必要があります。関連性に使用されます。
couponcodestring注文に適用されたプロモーションコード(ある場合)。関連性に使用されます。
newcustomerboolean初回購入者かどうか。関連性に使用されます。
customertypestringguest または logged_in。関連性に使用されます。
valuedecimal顧客の累積購入価値。関連性に使用されます。
subscriptionstatusstring該当する場合のサブスクリプション状態(active, trial, churned, paused, none)。関連性と適格性に使用されます。
customersegmentstringパートナー内部セグメンテーション(例: vip, at_risk, new, reactivated)。関連性に使用されます。
paymenttypestring選択された支払い方法 (credit_card, paypal, apple_pay など)。Pay+ の適格性に使用されます。
paymentServiceProviderstring画面で受け入れられる支払い方法のカンマ区切りリスト (例: applepay,paypal,cardpayment)。値は小文字でスペースを含まない必要があります。受け入れられる値の完全なリストについては、Payment Service Provider を参照してください。Pay+ の適格性に使用されます。
ccbinstringクレジットカードのBIN (6-8桁)。関連性に使用されます。
billingaddress1string請求先の住所。アイデンティティ解決と関連性に使用されます。
billingaddress2string請求先のアパート/ユニット。アイデンティティ解決に使用されます。
billingcitystring請求先の市区町村。関連性に使用されます。
billingstatestring請求先の州または県。関連性に使用されます。
billingzipcodestring請求先の郵便番号。アイデンティティ解決と関連性に使用されます。
billingnamestring請求先住所のカード名義人のフルネーム。アイデンティティ解決に使用されます。
shippingmethodstring選択された配送方法 (standard, express, next_day)。関連性に使用されます。
shippingnamestring配送先住所の受取人のフルネーム。関連性に使用されます。
shippingaddress1string配送先の住所。関連性に使用されます。
shippingcitystring配送先の市区町村。関連性に使用されます。
shippingstatestring配送先の州または県。関連性に使用されます。
shippingzipcodestring配送先の郵便番号。関連性に使用されます。
shippingcountrystring配送先の国 (ISO 3166-1 alpha-2)。関連性に使用されます。
partnerpaymentreferencestring顧客の保存された支払い方法の推測不可能な識別子。Shoppable Ads カードの転送に使用されます。
last4digitsstring使用されたカードの最後の4桁。アイデンティティ解決に使用されます。
plccstring"yes" または "no" — 顧客がプライベートラベルのクレジットカードを持っているかどうか。Pay+ の関連性に使用されます。
discountamountdecimal注文レベルで適用された割引。Pay+ の関連性に使用されます。
prescreenstring"yes" または "no" — 顧客がクレジットオファーの事前審査を受けたかどうか。Pay+ の関連性に使用されます。
adsexperiencestringShoppable Adsのエクスペリエンスをターゲットにする場合は、"shoppable"を渡します。
Placement position

オーバーレイプレースメントは、Roktが管理するコンテナ内で確認画面の上にレンダリングされ、アプリの既存のレイアウトに変更を加える必要はありません。

オーバーレイプレースメントを挿入するには、確認画面が読み込まれた後にselectPlacementsを呼び出します:

Overlay placement
import com.mparticle.MParticle
import com.mparticle.rokt.RoktConfig

val attributes = mapOf(
// Identity
"email" to "j.smith@example.com",
"firstname" to "Jenny",
"lastname" to "Smith",
"mobile" to "+13125551515",

// Transaction
"confirmationref" to "54321",
"currency" to "USD",
"country" to "US",
"language" to "en",
"totalprice" to "149.99",
"couponcode" to "SUMMER20",

// Customer context
"newcustomer" to "false",
"customertype" to "logged_in",
"value" to "2340.00",
"subscriptionstatus" to "active",
"customersegment" to "vip",

// Payment (include paymenttype and paymentServiceProvider for Pay+)
"paymenttype" to "credit_card",
"paymentServiceProvider" to "cardpayment",
"ccbin" to "411112",

// Billing address
"billingaddress1" to "123 Main St",
"billingcity" to "Brooklyn",
"billingstate" to "NY",
"billingzipcode" to "11201",

// Shipping
"shippingmethod" to "express",
"shippingaddress1" to "175 Varick St",
"shippingcity" to "New York",
"shippingstate" to "NY",
"shippingzipcode" to "10014",
"shippingcountry" to "US"
)

val roktConfig = RoktConfig.Builder().colorMode(RoktConfig.ColorMode.LIGHT).build()

MParticle.getInstance()?.Rokt()?.selectPlacements(
identifier = "RoktExperience",
attributes = attributes,
config = roktConfig
)

オプション機能オプション機能 への直接リンク

機能目的
Rokt.close()オーバーレイプレースメントを自動的に閉じます。

追加設定追加設定 への直接リンク

オプションのパラメータとしてRoktConfigを渡し、プレースメントUIをカスタマイズします(例:ダーク/ライトモード、キャッシング)。フォントの書体は、PostScript名をTypefaceオブジェクトにマップとして提供することもできます。

selectPlacements with RoktConfig and font typefaces
val fontTypefaces: MutableMap<String, WeakReference<android.graphics.Typeface>> = HashMap()
fontTypefaces["Arial-Bold"] = WeakReference(yourTypefaceObject)

val roktConfig = RoktConfig.Builder().colorMode(RoktConfig.ColorMode.LIGHT).build()

MParticle.getInstance()?.Rokt()?.selectPlacements(
identifier = "RoktExperience",
attributes = attributes,
fontTypefaces = fontTypefaces,
config = roktConfig
)
注記

識別子RoktExperienceまたは埋め込み識別子RoktEmbedded1を別の値に更新したい場合は、Roktアカウントマネージャーに連絡して、Roktプレースメントが一貫して設定されていることを確認してください。

Events APIEvents API への直接リンク

SDK+は、MParticle.getInstance()?.Rokt()?.events APIを通じて、配置のライフサイクルイベントをストリームとして提供します。Kotlin Flowを使用して、SDK+が生成するイベントを消費します。

Subscribe to Placement Events
import com.mparticle.MParticle

// owner: LifecycleOwner
owner.lifecycleScope.launch {
owner.lifecycle.repeatOnLifecycle(Lifecycle.State.CREATED) {
MParticle.getInstance()?.Rokt()?.events("RoktExperience")?.collect { roktEvent ->
// Handle the event
}
}
}

標準イベント標準イベント への直接リンク

すべての標準イベントを表示
イベント説明パラメータ
ShowLoadingIndicatorSDK+がRoktバックエンドを呼び出す前にトリガーされます。
HideLoadingIndicatorSDK+がRoktバックエンドからの成功または失敗を受け取ったときにトリガーされます。
PlacementInteractive配置がレンダリングされ、操作可能になったときにトリガーされます。placementId: String
PlacementReady配置が表示準備が整ったが、まだコンテンツがレンダリングされていないときにトリガーされます。placementId: String
OfferEngagementユーザーがオファーに関与したときにトリガーされます。placementId: String
PositiveEngagementユーザーがオファーに対して積極的に関与したときにトリガーされます。placementId: String
FirstPositiveEngagementユーザーが初めてオファーに対して積極的に関与したときにトリガーされます。placementId: String, fulfillmentAttributes: FulfillmentAttributes
OpenUrlユーザーがパートナーアプリに送信するように設定されたURLを押したときにトリガーされます。placementId: String, url: String
PlacementClosedユーザーによって配置が閉じられたときにトリガーされます。placementId: String
PlacementCompletedオファーの進行が終了し、表示するオファーがなくなったときにトリガーされます。また、キャッシュがヒットしたが、以前に却下されたために取得されたプレースメントが表示されない場合にもトリガーされます。placementId: String
PlacementFailureプレースメントが何らかの失敗により表示できなかった場合、または表示するプレースメントがない場合にトリガーされます。placementId: String (optional)
CartItemInstantPurchaseユーザーによってカタログアイテムの購入が開始されたときにトリガーされます。placementId: String, cartItemId: String, catalogItemId: String, currency: String, description: String, linkedProductId: String, totalPrice: Double, quantity: Int, unitPrice: Double

グローバルイベントグローバルイベント への直接リンク

特定のプレースメントに結びつかないSDK+レベルのイベントを購読するには、Rokt.globalEvents()を使用します。

Subscribe to global events
import com.rokt.roktsdk.RoktEvent

// owner: LifecycleOwner
owner.lifecycleScope.launch {
Rokt.globalEvents().collect { event ->
if (event is RoktEvent.InitComplete) {
// SDK+ initialization is complete
}
}
}

7. Appendix#

付録A: アプリ設定付録A: アプリ設定 への直接リンク

アプリケーションは、RoktConfigを通じて設定を渡すことができ、Android SDK+がシステムのデフォルトではなくアプリのカスタム設定を使用するようにします。

ColorModeオブジェクトColorModeオブジェクト への直接リンク

説明
LIGHTアプリケーションはライトモードです
DARKアプリケーションはダークモードです
SYSTEMアプリケーションはシステムのカラーモードをデフォルトとします

EdgeToEdgeDisplayEdgeToEdgeDisplay への直接リンク

説明
true (default)アプリケーションはエッジからエッジへの表示モードをサポートしています
falseアプリケーションはエッジからエッジへの表示モードをサポートしていません
RoktConfig with ColorMode and EdgeToEdgeDisplay
import com.mparticle.MParticle
import com.mparticle.rokt.RoktConfig

val roktConfig = RoktConfig.Builder()
.colorMode(RoktConfig.ColorMode.LIGHT)
.edgeToEdgeDisplay(true)
.build()

MParticle.getInstance()?.Rokt()?.selectPlacements(
identifier = "RoktExperience",
attributes = attributes,
config = roktConfig
)

CacheConfigオブジェクトCacheConfigオブジェクト への直接リンク

パラメータ説明
cacheDurationInSecondsRokt SDK+がエクスペリエンスをキャッシュする秒単位のオプションの期間です。最大許容値は90分で、指定されていないか無効な場合はデフォルトで90分です。
cacheAttributesキャッシュキーとして使用されるオプションの属性です。nullの場合、selectPlacementsで送信されたすべての属性がキャッシュキーとして使用されます。
Cache for 1200 seconds
import com.mparticle.rokt.CacheConfig
import com.mparticle.rokt.RoktConfig

// Cache the experience for 1200 seconds, using email and orderNumber as the cache key.
val roktConfig = RoktConfig.Builder()
.cacheConfig(CacheConfig(
cacheDurationInSeconds = 1200,
cacheAttributes = mapOf("email" to "j.smith@example.com", "orderNumber" to "123")
))
.build()

MParticle.getInstance()?.Rokt()?.selectPlacements(
identifier = "RoktExperience",
attributes = attributes,
config = roktConfig
)

Appendix B: Jetpack ComposeサポートとRoktLayoutAppendix B: Jetpack ComposeサポートとRoktLayout への直接リンク

Jetpack Composeを使用して実装された画面の場合、SDK+はRoktプレースメントのモダンで宣言的な統合のためにRoktLayoutコンポーザブルを提供します。RoktLayoutは、selectPlacementsを手動で呼び出すことなく、Overlay、BottomSheet、およびEmbeddedプレースメントタイプをサポートします。

Jetpack Compose placement with RoktLayout
import com.mparticle.kits.RoktLayout
import com.mparticle.MpRoktEventCallback
import com.mparticle.UnloadReasons

@Composable
fun MainScreen(modifier: Modifier = Modifier) {
Column(
modifier = modifier
.background(Color.LightGray)
.padding(8.dp),
) {
val attributes = mapOf(
"email" to "j.smith@example.com",
"firstname" to "Jenny",
"lastname" to "Smith",
"billingzipcode" to "90210",
"confirmationref" to "54321"
)
val callbacks = object : MpRoktEventCallback {
override fun onLoad() = println("View loaded")
override fun onUnload(reason: UnloadReasons) = println("View unloaded due to: $reason")
override fun onShouldShowLoadingIndicator() = println("Show loading indicator")
override fun onShouldHideLoadingIndicator() = println("Hide loading indicator")
}
val roktConfig = RoktConfig.Builder()
.colorMode(RoktConfig.ColorMode.DARK)
.cacheConfig(CacheConfig(
cacheDurationInSeconds = 1200,
cacheAttributes = mapOf("email" to "j.smith@example.com")
))
.build()

RoktLayout(
sdkTriggered = true,
identifier = "RoktExperience",
attributes = attributes,
location = "RoktEmbedded1",
modifier = Modifier
.fillMaxWidth()
.background(Color.Black),
mpRoktEventCallback = callbacks,
config = roktConfig
)
}
}

パラメータパラメータ への直接リンク

パラメータ説明
sdkTriggeredBooleanプレースメントをトリガーするタイミングを制御します。
identifierStringRoktエクスペリエンスの識別子(例: "RoktExperience")。
locationString?埋め込みプレースメントのためのオプションのロケーション名(例: "RoktEmbedded1")。
attributesMap<String, String>プレースメントに渡す属性のマップ。
modifierModifierレイアウト、スタイリング、UIの動作をカスタマイズするためのCompose Modifier
mpRoktEventCallbackMpRoktEventCallbackプレースメントイベント(ロード、アンロード、ロード状態)を処理するためのオプションのコールバック。
configRoktConfig?カラーモード、キャッシングなどのためのオプションの設定。

Appendix C: エラーハンドリングAppendix C: エラーハンドリング への直接リンク

IDSync APIはアプリの状態にとって中心的なものであり、高速で高可用性を持つように設計されています。アプリがインターネット接続なしでユーザーのログイン、ログアウト、または状態の変更を防ぐのと同様に、これらのAPIをゲート操作として扱い、一貫したユーザー状態を維持します。SDK+はAPIコールを自動的に再試行しませんが、ビジネスロジックに応じて再試行できるようにコールバックAPIを提供します。

エラーハンドリングを実装しない場合、大規模なデータの一貫性の問題が発生する可能性があります。

SDK+は常に基礎となるHTTPレスポンスのHTTPステータスとボディを返します。クライアント側の問題(デバイスの範囲外、クライアント側のタイムアウト、無効なアイデンティティリクエスト)については、SDK+はIdentityApi.UNKNOWN_ERRORとともに情報的なエラーメッセージを返します。

IDSync error handling
MParticle.getInstance()?.Identity()?.identify(identifyRequest)
?.addFailureListener { identityHttpResponse ->
if (identityHttpResponse?.httpCode == IdentityApi.UNKNOWN_ERROR) {
// Device is likely offline — retry the request
} else if (identityHttpResponse?.httpCode == IdentityApi.THROTTLE_ERROR) {
// Throttled (429) — retry with backoff
}
}
?.addSuccessListener { identityApiResult ->
// Proceed with the identified user
}
IDSync error handling
MParticle.getInstance().Identity().identify(identifyRequest)
.addFailureListener(new TaskFailureListener() {
@Override
public void onFailure(IdentityHttpResponse identityHttpResponse) {
if (identityHttpResponse.getHttpCode() == IdentityApi.UNKNOWN_ERROR) {
// Device is likely offline — retry the request
} else if (identityHttpResponse.getHttpCode() == IdentityApi.THROTTLE_ERROR) {
// Throttled (429) — retry with backoff
}
}
})
.addSuccessListener(new TaskSuccessListener() {
@Override
public void onSuccess(IdentityApiResult identityApiResult) {
// Proceed with the identified user
}
});

付録 D: WebからネイティブへのセッションIDの受け渡し付録 D: WebからネイティブへのセッションIDの受け渡し への直接リンク

ユーザージャーニーがWebとネイティブプラットフォームの両方にまたがる場合、Web SDK+からAndroid SDK+にセッションIDを渡すことで、一貫したRoktセッションを維持できます。これは、ユーザーがWebView(支払いページなど)でアクションを完了し、ネイティブアプリに戻って確認を行うハイブリッドフローに役立ちます。

Web SDK+からセッションIDを取得するWeb SDK+からセッションIDを取得する への直接リンク

selectPlacementsを呼び出した後、セッションIDは選択コンテキストで利用可能です。

Retrieve sessionId from the selection context
const selection = await launcher.selectPlacements({
identifier: "checkout",
attributes: {
email: "user@example.com",
// ... other attributes
}
});

const sessionId = await selection.context.sessionId;
注記

The session ID is a unique GUID assigned to the current user journey. It is useful for debugging and for correlating a user's activity across your web and native surfaces.

ディープリンクを使用して、セッションIDをネイティブアプリに渡します。

Deep-link to native app
const deepLink = `myapp://confirmation?sessionId=${encodeURIComponent(sessionId)}`;
window.location.href = deepLink;

セッションIDの設定セッションIDの設定 への直接リンク

ディープリンクからセッションIDを抽出し、selectPlacementsを呼び出す前にSDK+に渡します。

Handle deep link and set sessionId
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

intent.data?.getQueryParameter("sessionId")?.let { sessionId ->
MParticle.getInstance()?.Rokt()?.setSessionId(sessionId)
}

// Proceed with your confirmation flow
}
Handle deep link and set sessionId
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Uri data = getIntent().getData();
if (data != null) {
String sessionId = data.getQueryParameter("sessionId");
if (sessionId != null) {
MParticle.getInstance().Rokt().setSessionId(sessionId);
}
}

// Proceed with your confirmation flow
}

注意事項注意事項 への直接リンク

  • セッションを使用するために、setSessionIdselectPlacementsの前に呼び出してください。
  • 空の文字列は無視され、セッションは更新されません。
  • セッションIDをクエリパラメータとして渡す際には、常にURLエンコードしてください。

8. Test Your Integration#

SDK+が正しく初期化され、イベントが正しくログに記録されることを確認するには:

1Enable verbose SDK+ logging#

初期化前に詳細なSDK+ログを有効にして、送信される内容を確認できるようにします。

Enable verbose SDK+ logging
MParticle.setLogLevel(MParticle.LogLevel.VERBOSE)

2Build and run your app#

environment = MParticle.Environment.Developmentでアプリをビルドして実行します。

3Trigger selectPlacements#

配置がレンダリングされるべき画面でselectPlacementsをトリガーし、配置がロードされることを確認します。

4Verify events#

イベントがログに記録され、identifyRequest呼び出しが成功することを確認します。

トラブルシューティングトラブルシューティング への直接リンク

プレースメントが表示されない、またはイベントが表示されない場合は、Android LogcatでRokt SDK+のエラーを確認してください。一般的な問題:

初期化エラー初期化エラー への直接リンク

  • credentials キーとシークレットがRoktアカウントマネージャーから提供された値と一致していることを確認してください。
  • MParticle.start(options)Application.onCreate() 内で、いかなる selectPlacementslogEvent 呼び出しの前に実行されていることを確認してください。

アイデンティティエラーアイデンティティエラー への直接リンク

identifyTask の失敗リスナーが発火した場合、エラーハンドリング を参照して IdentityApi のエラーコードと再試行ガイダンスを確認してください。エラーハンドリングを行わないと、大規模なデータ整合性の問題が発生する可能性があります。

プレースメントが表示されないプレースメントが表示されない への直接リンク

  • プレースメントの identifier (例: RoktExperience) がRoktアカウントマネージャーが設定したものと一致していることを確認してください。
  • 埋め込みプレースメントの場合、埋め込みビューの識別子 (例: RoktEmbedded1) がレイアウト設定と一致していることを確認してください。
  • 属性マップに少なくとも emailfirstnamelastnamebillingzipcode、および confirmationref が含まれていることを確認してください。

プロキシ使用時のSSLハンドシェイクエラープロキシ使用時のSSLハンドシェイクエラー への直接リンク

開発環境でテストしている際に、CharlesやProxymanのようなHTTPデバッグプロキシが動作している場合や、企業ネットワークプロキシの背後にいる場合にSSLハンドシェイクエラーが発生することがあります。これは予想される動作です: SDK+はSSL証明書をピン留めしており、プロキシは独自の証明書を提示してHTTPSをインターセプトするため、ピン留めが失敗します。

プロキシがSDK+トラフィックを検査できるようにするには、開発ビルドでピン留めを無効にし、setPinningDisabledInDevelopment(true)SDK+初期化スクリプト 内の NetworkOptions ビルダーに追加してください。

Disable SSL pinning for proxy debugging
val networkOptions = NetworkOptions.builder()
// Only takes effect in the development environment; production builds stay pinned.
.setPinningDisabledInDevelopment(true)
.build()
この記事は役に立ちましたか?