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的官网中都有介绍,关键说下测试流程
- 创建一个测试链接
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的账号之前测订阅等问题被加入为测试账号,要创建一个新的google账号来测试,不然refererUrl还是拿不到