a.導(dǎo)入包
implementation 'com.google.android.gms:play-services-analytics:18.0.1'
implementation 'com.android.installreferrer:installreferrer:2.2'
b.核心代碼
google文檔
private lateinit var sharedPreference: SharedPreferences
private lateinit var referrerClient: InstallReferrerClient
private val refererKey = "global_referer_key"
private fun initReferer() {
sharedPreference = getSharedPreferences("MainActivity", Context.MODE_PRIVATE)
if (sharedPreference.contains(refererKey)) {
val referrerUrl = sharedPreference.getString(refererKey, "")
Log.i("ZHP", "referrerUrl:「$referrerUrl」")
}
referrerClient = InstallReferrerClient.newBuilder(this).build()
referrerClient.startConnection(object : InstallReferrerStateListener {
override fun onInstallReferrerSetupFinished(responseCode: Int) {
when (responseCode) {
InstallReferrerClient.InstallReferrerResponse.OK -> {
val response: ReferrerDetails = referrerClient.installReferrer
val referrerUrl = response.installReferrer
Log.i("ZHP", "referrerUrl:「$referrerUrl」")
}
InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> {
// API not available on the current Play Store app.
Log.i("ZHP", "referrerUrl:organic:FEATURE_NOT_SUPPORTED")
}
InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE -> {
// Connection couldn't be established.
Log.i("ZHP", "referrerUrl:organic:SERVICE_UNAVAILABLE")
}
}
}
override fun onInstallReferrerServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
Log.i("ZHP", "referrerUrl:organic:onInstallReferrerServiceDisconnected")
}
})
}
AndroidManifest.xml配置
<activity>
...
</activity>
<service android:name="com.google.analytics.tracking.android.CampaignTrackingService" />
<receiver
android:name="com.google.analytics.tracking.android.CampaignTrackingReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>
c 測(cè)試
代碼在google的官網(wǎng)中都有介紹,關(guān)鍵說下測(cè)試流程
- 創(chuàng)建一個(gè)測(cè)試鏈接
https://play.google.com/store/apps/details?id=<com.xx.xx> //yourAppId
&referrer=utm_source%3Dgoogle%26utm_medium%3Dcpc%26utm_term%3Dpodcast%252Bapps%26utm_content%3DdisplayAd1%26utm_campaign%3Dpodcast%252Bgeneralkeywords
- 網(wǎng)頁打開測(cè)試鏈接,正確彈出你的app頁面
- 點(diǎn)擊在google play中打開(記得提前卸載app)
- 在google play下載頁面,選擇adb或者as安裝debug包
adb install -r app-debug.apk
- 安裝成功后在google play頁面點(diǎn)擊啟動(dòng)
備注:如果google play的賬號(hào)之前測(cè)訂閱等問題被加入為測(cè)試賬號(hào),要?jiǎng)?chuàng)建一個(gè)新的google賬號(hào)來測(cè)試,不然refererUrl還是拿不到