Интеграция SDK
Узнайте, как инициализировать и запустить SDK Android.
Рекомендуется
Get started with our SDK integration wizard
- Необходимо установить SDK для Android.
- Убедитесь, что в файле
build.gradle
вашего приложения значениеapplicationId
(в блокеdefaultConfig
) совпадает с идентификатором приложения в AppsFlyer. - Получите ключ разработчика AppsFlyer. Он необходим для успешной инициализации SDK.
Инициализация SDK Android
Рекомендуется инициализировать SDK внутри глобального класса/подкласса Application. Так SDK сможет запуститься в любом сценарии (например, при диплинкинге).
Шаг 1. Импорт AppsFlyerLib
В глобальном классе Application импортируйте AppsFlyerLib
:
import com.appsflyer.AppsFlyerLib;
import com.appsflyer.AppsFlyerLib
Шаг 2. Инициализация SDK
В глобальном классе Application onCreate
, call init
со следующими аргументами:
AppsFlyerLib.getInstance().init(<YOUR_DEV_KEY>, null, this);
AppsFlyerLib.getInstance().init(<YOUR_DEV_KEY>, null, this)
- Первый аргумент — ваш ключ разработчика AppsFlyer.
- Второй аргумент — допускающий значение null
AppsFlyerConversionListener
. Если вам не нужны данные о конверсиях, рекомендуем передаватьnull
в качестве второго аргумента. Дополнительные сведения см. в статье Данные о конверсиях. - Третий аргумент — контекст приложения.
Запуск SDK Android
В методе onCreate
класса Application после вызова init
, call start
и передайте ему контекст приложения в качестве первого аргумента:
AppsFlyerLib.getInstance().start(this);
AppsFlyerLib.getInstance().start(this)
Deferring SDK start
Необязательно
Вы можете отложить инициализацию SDK, вызвав start
из класса Activity, а не из класса Application. init
должен по-прежнему вызываться в классе Application.
Обычно отложенный запуск SDK используется, когда приложение запрашивает у пользователя разрешение на сбор данных в основной активности и вызывает start
после его получения.
Важное замечание
Если приложение вызывает
start
из класса Activity, оно должно передать контекст активности Activity Context в SDK.
Если не передать контекст активности, SDK не сработает, что приведет к потере данных атрибуции и событий в приложении.
Starting with a response listener
Чтобы получать подтверждение успешного запуска SDK, создайте объект AppsFlyerRequestListener
и передайте его в качестве третьего аргумента start
:
AppsFlyerLib.getInstance().start(getApplicationContext(), <YOUR_DEV_KEY>, new AppsFlyerRequestListener() {
@Override
public void onSuccess() {
Log.d(LOG_TAG, "Launch sent successfully, got 200 response code from server");
}
@Override
public void onError(int i, @NonNull String s) {
Log.d(LOG_TAG, "Launch failed to be sent:\n" +
"Error code: " + i + "\n"
+ "Error description: " + s);
}
});
AppsFlyerLib.getInstance().start(this, <YOUR_DEV_KEY>, object : AppsFlyerRequestListener {
override fun onSuccess() {
Log.d(LOG_TAG, "Launch sent successfully")
}
override fun onError(errorCode: Int, errorDesc: String) {
Log.d(LOG_TAG, "Launch failed to be sent:\n" +
"Error code: " + errorCode + "\n"
+ "Error description: " + errorDesc)
}
})
- The
onSuccess()
вызывается для каждого ответа200
на запрос атрибуции, посланный пакетом SDK. - The
onError(String error)
выполняется для любого другого ответа и возвращается ответ в виде строки ошибки.
Полный пример
В следующем примере показано, как инициализировать и запустить SDK из класса Application.
import android.app.Application;
import com.appsflyer.AppsFlyerLib;
// ...
public class AFApplication extends Application {
// ...
@Override
public void onCreate() {
super.onCreate();
// ...
AppsFlyerLib.getInstance().init(<YOUR_DEV_KEY>, null, this);
AppsFlyerLib.getInstance().start(this);
// ...
}
// ...
}
import android.app.Application
import com.appsflyer.AppsFlyerLib
// ...
class AFApplication : Application() {
override fun onCreate() {
super.onCreate()
// ...
AppsFlyerLib.getInstance().init(<YOUR_DEV_KEY>, null, this)
AppsFlyerLib.getInstance().start(this)
// ...
}
// ...
}
Настройка Customer User ID (идентификатора клиента)
Необязательно
The Customer User ID (CUID) is a unique user identifier created by the app owner outside the SDK. It can be associated with in-app events if provided to the SDK. Once associated with the CUID, these events can be cross-referenced with user data from other devices and applications.
Set the customer User ID
Once the CUID is available, you can set it by calling setCustomerUserId
.
...
AppsFlyerLib.getInstance().init(<YOUR_DEV_KEY>, conversionListener, this);
AppsFlyerLib.getInstance().start(this , <YOUR_DEV_KEY> );
...
// Do your magic to get the customerUserID...
...
AppsFlyerLib.getInstance().setCustomerUserId(<MY_CUID>);
The CUID can only be associated with in-app events after it was set. Since start
was called before setCustomerUserID
, the install event will not be associated with the CUID. If you need to associate the install event with the CUID, see the below section.
Associate the CUID with the install event
If it’s important for you to associate the install event with the CUID, you should set it before calling start
.
You can set the CUID before start
in two ways, depending on whether you start the SDK in the Application
or the Activity
class.
When starting from the application class
Если вы запустили SDK из класса Application
class (see: Starting the Android SDK
) and you want the CUID to be associated with the install event, put the SDK in waiting mode to prevent the install data from being sent to AppsFlyer before the CUID is provided.
To activate the waiting mode, set waitForCustomerUserId
to true
after init
and before start
.
Важно
It's important to remember that putting the SDK in a waiting mode may block the SDK from sending the install event and consequently prevent attribution. This can occur, for example, when the user launches the application for the first time and then exits before the SDK can set the CUID.
AppsFlyerLib.getInstance().init(<YOUR_DEV_KEY>, getConversionListener(), getApplicationContext());
AppsFlyerLib.getInstance().waitForCustomerUserId(true);
AppsFlyerLib.getInstance().start(this);
После вызова start
, you can add your custom code that makes the CUID available.
Once the CUID is available, the final step includes setting the CUID, releasing the SDK from the waiting mode, and sending the attribution data with the customer ID to AppsFlyer. This step is performed using the call to setCustomerIdAndLogSession
.
AppsFlyerLib.getInstance().setCustomerIdAndLogSession(<CUSTOMER_ID>, this);
Кроме setCustomerIdAndLogSession
не используйте setCustomerUserId
или любую другую функциональность SDK AppsFlyer, так как приостановленный SDK будет игнорировать ее.
Note
If you wish to remove the waiting mode from the SDK initialization flow, it is not enough to delete the call to waitForCustomerUserId(true)
. Также требуется заменить его на waitForCustomerUserID(false)
. Простого удаления вызова недостаточно, поскольку флаг 'waitForCustomerUserId' хранится в общих настройках Android.
Пример кода
public class AFApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
AppsFlyerConversionListener conversionDataListener =
new AppsFlyerConversionListener() {
...
};
AppsFlyerLib.getInstance().init(<YOUR_DEV_KEY>, getConversionListener(), getApplicationContext());
AppsFlyerLib.getInstance().waitForCustomerUserId(true);
AppsFlyerLib.getInstance().start(this);
// Do your magic to get the customerUserID
// any AppsFlyer SDK code invoked here will be discarded
// ...
// Once the customerUserID is available, call setCustomerIdAndLogSession().
// setCustomerIdAndLogSession() sets the CUID, releases the waiting mode,
// and sends the attribution data with the customer ID to AppsFlyer.
AppsFlyerLib.getInstance().setCustomerIdAndLogSession(<CUSTOMER_ID>, this);
}
}
When starting from the Activity class
Если вы запустили SDK из класса Activity
(see: Deferring SDK start
) class and you want the CUID to be associated with the install event, set the CUID beforestart
.
Log sessions
The SDK sends an af_app_opened
message whenever the app is opened or brought to the foreground. Before the message is sent, the SDK makes sure that the time passed since sending the last message is not smaller than a predefined interval.
Setting the time interval between app launches
Вызовите setMinTimeBetweenSessions
to set the minimal time interval that must lapse between two af_app_opened
messages. The default interval is 5 seconds.
Logging sessions manually
You can log sessions manually by calling logSession
.
Включение режима отладки
Необязательно
Чтобы включить журналы отладки, вызовите setDebugLog
:
AppsFlyerLib.getInstance().setDebugLog(true);
AppsFlyerLib.getInstance().setDebugLog(true)
Примечание
Для просмотра полных журналов отладки необходимо вызвать
setDebugLog
до вызова других методов SDK.См. пример.
Предупреждение
Чтобы не допустить утечки конфиденциальных данных, перед распространением приложения обязательно убедитесь, что журналы отладки отключены.
Тестирование интеграции
Необязательно
Подробные инструкции приведены в руководстве по тестированию интеграции SDK для Android.
Изменения сохранены 4 месяца назад