a.導入包
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 測試
代碼在google的官網中都有介紹,關鍵說下測試流程
- 創(chuàng)建一個測試鏈接
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
- 網頁打開測試鏈接,正確彈出你的app頁面
- 點擊在google play中打開(記得提前卸載app)
- 在google play下載頁面,選擇adb或者as安裝debug包
adb install -r app-debug.apk
- 安裝成功后在google play頁面點擊啟動
備注:如果google play的賬號之前測訂閱等問題被加入為測試賬號,要創(chuàng)建一個新的google賬號來測試,不然refererUrl還是拿不到