> For the complete documentation index, see [llms.txt](https://docs.dfinery.ai/developer-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.dfinery.ai/developer-guide/platform/android/integration.md).

# 연동하기

이 문서는 DFINERY SDK를 Android에 통합하는 방법을 다룹니다. DFINERY SDK를 설치하면 이벤트 분석 기능과 유저 프로필 기능 그리고 액션 기능이 제공됩니다.

더 자세히 알아보려면 [리소스 및 샘플](/developer-guide/common/resource-and-sample.md)을 참조하세요.

## 시작하기 전에

### 서비스 설정

[DFINERY 콘솔](https://console.dfinery.ai/)의 서비스 관리/서비스 정보 페이지에서 데이터 소스 항목에 Android를 체크하셔야 합니다.

![서비스 정보](/files/kByxg9Ww4QXDmsd2ecNT)

### 지원 정보

* 최소 지원 SDK : Android 4.4+ / API 19+
* 컴파일 SDK : 34

### 의존성

* [com.google.android.gms:play-services-appset](https://mvnrepository.com/artifact/com.google.android.gms/play-services-appset)

## SDK 설치

### 의존성 추가하기

앱에서 DFINERY SDK의 의존성을 적용하려면 다음 단계를 완료하세요.

#### 1. maven 의존성을 가져오기 위해 repositories 내에 `mavenCentral`을 추가합니다.

{% tabs %}
{% tab title="build.gradle (Gradle 3.5 이전)" %}

```groovy
allprojects {
    repositories {
        mavenCentral()
    }
}
```

{% endtab %}

{% tab title="settings.gradle (Gradle 3.5 이후)" %}

```groovy
pluginManagement {
    repositories {
        mavenCentral()
    }
}
dependencyResolutionManagement {
    repositories {
        mavenCentral()
    }
}
```

{% endtab %}
{% endtabs %}

#### 2. 앱의 모듈 디렉터리 내에 있는 `build.gradle` 파일을 엽니다.

#### 3. dependencies에 [최신 버전의 DFINERY SDK](https://github.com/IGAWorksDev/dfinery-android-sdk/releases)와 필요한 요소에 대해 SDK 종속 항목을 추가합니다.

{% hint style="info" %}
DFINERY는 AppSetId를 수집하기 위해 [play-services-appset](https://developer.android.com/training/articles/app-set-id) 의존성을 필요로 합니다.
{% endhint %}

{% tabs %}
{% tab title="build.gradle" %}

```groovy
 dependencies {
  implementation 'com.google.android.gms:play-services-appset:16.0.2'
  //Get the latest version from https://mvnrepository.com/artifact/com.igaworks.dfinery/android-sdk
  implementation 'com.igaworks.dfinery:android-sdk:HERE_LATEST_VERSION'
}
```

{% endtab %}

{% tab title="build.gradle.kts" %}

```groovy
 dependencies {
  implementation("com.google.android.gms:play-services-appset:16.0.2")
  //Get the latest version from https://mvnrepository.com/artifact/com.igaworks.dfinery/android-sdk
  implementation("com.igaworks.dfinery:android-sdk:HERE_LATEST_VERSION")
}
```

{% endtab %}
{% endtabs %}

## SDK 초기화

### 초기화 하기

앱에서 DFINERY SDK를 초기화하려면 다음 단계를 완료하세요.

#### 1. Application을 상속한 객체를 생성합니다. 상속한 객체가 이미 있을 경우 해당 객체를 사용합니다.

{% tabs %}
{% tab title="Java" %}

```java
public class BaseApplication extends Application
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
class BaseApplication: Application()
```

{% endtab %}
{% endtabs %}

#### 2. Application을 상속한 객체에서 [onCreate()](https://developer.android.com/reference/android/app/Application#onCreate\(\)) 메소드를 Override 합니다.

{% tabs %}
{% tab title="Java" %}

```java
@Override
public void onCreate() {
    super.onCreate();
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
override fun onCreate() {
    super.onCreate()
}
```

{% endtab %}
{% endtabs %}

#### 3. onCreate() 메소드 내에 다음 코드를 작성합니다.

> Service ID는 [DFINERY Console](https://console.dfinery.ai/)의 `서비스 관리/서비스 정보/Key 정보/서비스키` 경로에서 확인이 가능합니다.

{% tabs %}
{% tab title="Java" %}

```java
Dfinery.getInstance().init(this, "{YOUR_SERVICE_ID}");
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
Dfinery.getInstance().init(this, "{YOUR_SERVICE_ID}")
```

{% endtab %}
{% endtabs %}

다음 코드 스니펫은 초기화 작성 완료 시의 예를 보여줍니다.

{% tabs %}
{% tab title="Java" %}

```java
public class BaseApplication extends Application{
    @Override
    public void onCreate() {
        super.onCreate();
        Dfinery.getInstance().init(this, "{YOUR_SERVICE_ID}");
    }
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
class BaseApplication: Application(){
    override fun onCreate() {
        super.onCreate()
        Dfinery.getInstance().init(this, "{YOUR_SERVICE_ID}")
    }
}
```

{% endtab %}
{% endtabs %}

#### 4. AndroidManifest.xml에 작성한 Application을 등록합니다.

```xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application
        android:name=".BaseApplication">
    </application>
</manifest>
```

#### 5. AndroidManifest.xml에 필요한 권한을 추가합니다.

```xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
```

### 구글 광고 ID 설정하기(선택사항)

Google 광고 ID를 수집하기 위해선 `setGoogleAdvertisingId()` 메소드를 통해 수동으로 설정해야합니다.

#### 1. 앱의 모듈 디렉터리 내에 있는 `build.gradle` 파일을 엽니다.

#### 2. dependencies에 [광고 ID를 수집하기 위해 필요한 종속 항목](https://developers.google.com/android/guides/setup)을 추가합니다.

{% tabs %}
{% tab title="build.gradle" %}

```groovy
 dependencies {
  implementation 'com.google.android.gms:play-services-ads-identifier:18.0.1'
}
```

{% endtab %}

{% tab title="build.gradle.kts" %}

```groovy
 dependencies {
  implementation("com.google.android.gms:play-services-ads-identifier:18.0.1")
}
```

{% endtab %}
{% endtabs %}

#### 3. AndroidManifest.xml에 필요한 권한을 추가합니다.

```xml
<uses-permission android:name="com.google.android.gms.permission.AD_ID" />
```

#### 4. `setGoogleAdvertisingId()` 메소드를 통해 광고 ID를 설정합니다.

{% hint style="success" %}
광고 ID 수집 로직은 별도의 스레드에서 동작해야 합니다. 아래 코드 스니펫은 Thread를 생성하여 동작했지만, 필요에 따라 다른 방법(AsyncTask, 코루틴 등)을 사용하여도 됩니다.
{% endhint %}

{% tabs %}
{% tab title="Java" %}

```java
new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            AdvertisingIdClient.Info idInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
            DfineryProperties.setGoogleAdvertisingId(idInfo.getId(), idInfo.isLimitAdTrackingEnabled());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}).start();
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
Thread {
    try {
        val idInfo = AdvertisingIdClient.getAdvertisingIdInfo(
            applicationContext
        )
        DfineryProperties.setGoogleAdvertisingId(idInfo.id, idInfo.isLimitAdTrackingEnabled)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}.start()
```

{% endtab %}
{% endtabs %}

## SDK 설정

SDK 초기화 시에 로그 활성화 등의 옵션을 설정할 수 있습니다.

### 로그 활성화 하기

로그 활성화는 DFINERY의 설정을 적용하는 DfineryConfig를 사용하여 설정 가능합니다. DfineryConfig는 `init()` 메소드 호출 시에 파라미터로 넣어 적용하거나 `res/values/dfinery.xml`을 사용하여 설정 할 수 있습니다.

```java
setLogEnable(boolean enable)
```

* 첫 번째 인자인 `enable`은 로그를 표시할지 말지 설정하는 값입니다. 기본값은 `false`입니다.

{% hint style="success" %}
`BuildConfig.DEBUG` 값을 넣어 디버그 모드일때만 로그가 출력 되고 배포시에는 출력되지 않게끔 설정할 수 있습니다.
{% endhint %}

{% tabs %}
{% tab title="Java" %}

```java
DfineryConfig config = new DfineryConfig.Builder()
    .setLogEnable(true)
    .build();
Dfinery.getInstance().init(this, "{YOUR_SERVICE_ID}", config);
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val config = DfineryConfig.Builder()
    .setLogEnable(true)
    .build()
Dfinery.getInstance().init(this, "{YOUR_SERVICE_ID}", config)
```

{% endtab %}

{% tab title="dfinery.xml" %}

```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="com_igaworks_dfinery_log_enable" translatable="false">true</bool>
</resources>
```

{% endtab %}
{% endtabs %}

### 로그 레벨 변경하기

로그 레벨은 Dfinery의 설정을 적용하는 DfineryConfig를 사용하여 설정 가능합니다. DfineryConfig는 `init()` 메소드 호출 시에 파라미터로 넣어 적용하거나 `res/values/dfinery.xml`을 사용하여 설정 할 수 있습니다.

{% hint style="info" %}
로그 레벨 값은 [`android.util.Log`](https://developer.android.com/reference/android/util/Log#constants_1)의 상수 값의 정의를 따릅니다.
{% endhint %}

```java
setLogLevel(int logLevel)
```

* 첫번째 인자인 `logLevel`은 로그 표시 레벨을 설정하는 값입니다. 기본값은 `Log.ERROR(6)` 입니다.

{% tabs %}
{% tab title="Java" %}

```java
DfineryConfig config = new DfineryConfig.Builder()
    .setLogLevel(Log.DEBUG)
    .build();
Dfinery.getInstance().init(this, "{YOUR_SERVICE_ID}", config);
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val config = DfineryConfig.Builder()
    .setLogLevel(Log.DEBUG)
    .build()
Dfinery.getInstance().init(this, "{YOUR_SERVICE_ID}", config)
```

{% endtab %}

{% tab title="dfinery.xml" %}

```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="com_igaworks_dfinery_log_level">2</integer>
</resources>
```

{% endtab %}
{% endtabs %}

## 완료

SDK 설치 및 초기화가 완료되었습니다.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.dfinery.ai/developer-guide/platform/android/integration.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
