在 Android 上,如果你想知道用户是从 Google Play 商店链接打开应用程序的,你可以使用 Google Play Install Referrer API 来获取referrer信息。这个API允许你获取用户从哪个来源安装或启动你的应用的详细信息。
以下是如何实现这个功能的步骤:
在你的 build.gradle
(Module: app) 文件中添加以下依赖:
dependencies {
implementation 'com.android.installreferrer:installreferrer:2.2'
}
在你的应用启动时(例如在 Application
类的 onCreate
方法中),初始化 InstallReferrerClient
:
import com.android.installreferrer.api.InstallReferrerClient;
import com.android.installreferrer.api.InstallReferrerStateListener;
import com.android.installreferrer.api.ReferrerDetails;
public class MyApplication extends Application {
private InstallReferrerClient installReferrerClient;
@Override
public void onCreate() {
super.onCreate();
installRefiatorClient = InstallReferrerClient.newBuilder(this).build();
installReferrerClient.startConnection(new InstallReferrerStateListener() {
@Override
public void onInstallReferrerSetupFinished(int responseCode) {
switch (responseCode) {
case InstallReferrerResponse.OK:
// Connection established
fetchReferrer();
break;
case InstallReferrerResponse.FEATURE_NOT_SUPPORTED:
// API not available on the current Play Store app
break;
case InstallReferrerResponse.SERVICE_UNAVAILABLE:
// Connection could not be established
break;
}
}
@Override
public void onInstallReferrerServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}
});
}
private void fetchReferrer() {
try {
ReferrerDetails response = installReferrerClient.getInstallReferrer();
String referrerUrl = response.getInstallReferrer();
// Use the referrerUrl to determine the source
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onTerminate() {
super.onTerminate();
if (installReferrerClient != null) {
installReferrerClient.endConnection();
}
}
}
在 fetchReferrer
方法中,你可以获取到referrer URL,然后解析这个URL来确定用户是从哪个来源打开应用的。例如,如果referrer URL包含特定的查询参数或路径,你可以据此判断用户是从Google Play商店链接打开应用的。
private void fetchReferrer() {
try {
ReferrerDetails response = installRefiatorClient.getInstallRefiator();
String referrerUrl = response.getInstallReferrer();
if (referrerUrl != null && referrerUrl.startsWith("https://play.google.com")) {
// User opened the app from Google Play Store link
}
} catch (Exception e) {
e.printStackTrace();
}
}
InstallReferrerClient
应该在应用启动时初始化,并在应用终止时关闭连接。领取专属 10元无门槛券
手把手带您无忧上云