# SDK 설치 및 API 적용

## SDK 설치 및 초기화

### SDK 설치

#### **`프로젝트 수준의 build.gradle`**

프로젝트의 build.gradle ( root 파일 ) 에 아래와 같이 repository 주소를 추가해주세요.

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

```groovy
...
allprojects {
    repositories {
        google()
        mavenCentral()
        /* wisetracker sdk repository config */
        maven {
            def endPoint = "https://analytics.wisetracker.co.kr/console/android/sdk/github/credentials.do"
            url = uri(new URL(endPoint+'?name=URI').text)
            credentials {
                username = new URL(endPoint+'?name=USER').text
                password = new URL(endPoint+'?name=TOKEN').text
            }
        }
    }
}
...
buildscript {
  repositories {
    google()
    mavenCentral()
  }
  dependencies {
    ...
    /* Google services */
    classpath 'com.google.gms:google-services:4.3.15'  // Google Services plugin
    ...
  }
}
```

{% endtab %}
{% endtabs %}

#### **`Android 13 이상의 버전에서 푸시 알림 권한 획득을 위한 설정`**

`프로젝트 수준 혹은, app 수준 "build.gradle"의 "`targetSdkVersion = 33" 이상이어야 합니다.

```groovy
buildscript {
    ext {
        ...
        targetSdkVersion = 33
        ...
```

#### **`app모듈 수준의 build.gradle`**

프로젝트의 app/build.gradle 파일에 있는 `dependencies`에 아래와 같이 Wisetracker SDK를 추가해주세요.

<mark style="color:orange;">**`이 때, Java와 Kotlin에 따라 이용하는 모듈명이 달라집니다.`**</mark>

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

```groovy
...
// Add the following line:
apply plugin: 'com.google.gms.google-services'  // Google Services plugin
...

android {
  ...
}
...
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    ....
    // SDK 적용
    implementation "com.sdk.wisetracker:base_module:latest.release"
    implementation "com.sdk.wisetracker:new_dot_module:latest.release"
    
    // Import the BoM for the Firebase platform
    implementation platform('com.google.firebase:firebase-bom:29.0.0')
    
    // Declare the dependencies for the Firebase Cloud Messaging and Analytics libraries
    // When using the BoM, you don't specify versions in Firebase library dependencies
    implementation 'com.google.firebase:firebase-messaging'
}
...
```

{% endtab %}

{% tab title="gradle-Kotlin" %}

```groovy
...
// Add the following line:
apply plugin: 'com.google.gms.google-services'  // Google Services plugin
...

android {
  ...
}
...
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    ....
    // SDK 적용
    implementation "com.sdk.wisetracker:base_module:latest.release"
    implementation "com.sdk.wisetracker:new_dot_module:latest.release"
    
    // Import the BoM for the Firebase platform
    implementation platform('com.google.firebase:firebase-bom:29.0.0')
    
    // Declare the dependencies for the Firebase Cloud Messaging and Analytics libraries
    // When using the BoM, you don't specify versions in Firebase library dependencies
    implementation 'com.google.firebase:firebase-messaging-ktx'
}
...
```

{% endtab %}
{% endtabs %}

### AuthorizationKey 등록

#### **`app/res/values/strings.xml`**

프로젝트의 app/res/values/strings.xml 파일에 아래 코드를 추가합니다.\
&#x20;추가한 코드 중 3번 라인 `serviceNumber`의 value를 올바른 값으로 변경해야 합니다.

{% tabs %}
{% tab title="strings.xml" %}

```markup
...
<!--
  // =======================================================
  // 이 내용은 Wisetracker 기본 SDK가 이미 적용된 경우에는 새로 적용할
  // 필요가 없습니다.  메시징 서비스만 이용하는 경우 참조해주세요.
  // =======================================================
-->
<string-array name="dotAuthorizationKey">
    <item name="useMode">1</item>
    <item name="serviceNumber">xxxxx</item>
    <item name="expireDate">14</item>
    <item name="isDebug">false</item>
    <item name="isInstallRetention">true</item>
    <item name="isFingerPrint">true</item>
    <item name="accessToken"></item>
</string-array>
...
```

{% endtab %}
{% endtabs %}

\
&#x20;대시보드 화면 좌측 메뉴에서 "서비스 설정 > 어플리케이션 설정"화면에서 "서비스 번호"를 복사하여

"app/res/values/strings.xml"파일 3번 라인 `serviceNumber`의 value로 입력해주세요.

<figure><img src="/files/B4gIDpaeT0vfmTs7OzKJ" alt=""><figcaption><p>서비스번호 확인</p></figcaption></figure>

### HTTP 통신 허용

프로젝트의 Target API가 **API Level 28** 이상일 경우에 적용하는 설정입니다. 아래와 같이 HTTP 통신을 허용하는 두 가지 설정을 추가해주세요.\
\
하나는 "AndroidManifest.xml"설정이고\
다른 하나는 "network\_security\_config.xml"파일을 새로 만드는 것입니다.\
\
// =======================================================\
// 이 내용은 Wisetracker 기본 SDK가 이미 적용된 경우에는 새로 적용할\
// 필요가 없습니다. 메시징 서비스만 이용하는 경우 참조해주세요.\
// =======================================================

{% tabs %}
{% tab title="AndroidManifest.xml" %}

```markup
<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:networkSecurityConfig="@xml/network_security_config"
    android:theme="@style/AppTheme">
...
```

{% endtab %}
{% endtabs %}

#### **`app/res/xml/network_security_config.xml`**

해당 위치에 "network\_security\_config.xml"파일을 새로 생성합니다.

{% tabs %}
{% tab title="network\_security\_config.xml" %}

```markup
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">trk.analytics.wisetracker.co.kr</domain>
    </domain-config>
</network-security-config>
```

{% endtab %}
{% endtabs %}

### MainActivity 찾기

MainActivity에 구현되어야 하는 내용들을 설명하기 전에 내 앱의 Main 은 어떤 Activity 인지 알아야 합니다. 아래 구현되는 내용의 상당 부분은 MainActivity를 대상으로 합니다.

MainActivity는 앱이 실행될 때 처음으로 시작되는 위치를 가리키며 "AndroidManifest.xml"파일에 아래와 같은 "intent-filter"가 적용된 Activity입니다.

```xml
<!--
  // =======================================================
  // 아래와 같은 "intent-filter"가 적용된 activity가 Main입니다.
  // 아래 "AndroidManifest.xml"내용을 참조해주세요.
  // =======================================================
-->
<intent-filter>
  <action android:name="android.intent.action.MAIN" />
  <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
```

{% tabs %}
{% tab title="AndroidManifest.xml" %}

```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.support.wisetracker">

  <application
      ...>
    ...
    <activity
        android:name=".MainActivity"
        android:exported="true"
        android:screenOrientation="fullSensor"
        android:theme="@style/Theme.SdkSample.NoActionBar">
      <!--
        // =======================================================
        // 아래와 같은 "intent-filter"가 적용된 activity가 Main입니다.
        // =======================================================
      -->
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    ...
  </application>

</manifest>
```

{% endtab %}
{% endtabs %}

### 초기화

Application을 상속받는 클래스가 아닌 `Activity`를 상속받는 기본 화면의 `onCreate()` 메쏘드에 적용해 주세요

`MainActivity`

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

```java
import com.sdk.wisetracker.new_dot.open.DOT;

public class MainActivity extends AppCompatActivity {
  ...
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    ...
    // =======================================================
    // 이 내용은 Wisetracker 기본 SDK가 이미 적용된 경우에는 새로 적용할
    // 필요가 없습니다.  메시징 서비스만 이용하는 경우 참조해주세요.
    // =======================================================
    // SDK 호출
    DOT.initialization(this);
    ...
  }
  ...
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
import com.sdk.wisetracker.new_dot.open.DOT

class MainActivity : AppCompatActivity() {
  ...
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    ...
    // =======================================================
    // 이 내용은 Wisetracker 기본 SDK가 이미 적용된 경우에는 새로 적용할
    // 필요가 없습니다.  메시징 서비스만 이용하는 경우 참조해주세요.
    // =======================================================
    // SDK 호출
    DOT.initialization(this)
    ...
  }
}
```

{% endtab %}
{% endtabs %}

## PushMessage API 적용

### Device Token 수집

푸시 메시지를 보내기 위해서는 우선 푸시 토큰을 수집해야 합니다. 우선 Activity 수준에서 푸시 토큰을 수집할 수 있도록 아래와 같이 설정합니다.

`MainActivity`

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

```java
public class MainActivity extends AppCompatActivity {
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);    
        ...
        // =======================================================
        // 이 내용은 Wisetracker 기본 SDK가 이미 적용된 경우에는 새로 적용할
        // 필요가 없습니다.  메시징 서비스만 이용하는 경우 참조해주세요.
        // =======================================================
        // SDK 호출
        DOT.initialization(this);

        // =======================================================
        // Start : Push 메시지 수신을 위한 설정 <-- 새로 추가된 부분
        // =======================================================
        FirebaseMessaging.getInstance().getToken()
            .addOnCompleteListener(new OnCompleteListener<String>() {
              @Override
              public void onComplete(@NonNull Task<String> task) {
                if (!task.isSuccessful()) {
                  Log.w("FCM", "Fetching FCM registration token failed", task.getException());
                  return;
                }
                // Get new FCM registration token
                String token = task.getResult();
                // 푸시 토큰 서버 전송
                DOT.setPushToken(token);
              }
            });
        // =======================================================
        // End : Push 메시지 수신을 위한 설정
        // =======================================================
        ...
    }
    ...
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
class MainActivity : AppCompatActivity() {
  ...
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    ...
    // =======================================================
    // 이 내용은 Wisetracker 기본 SDK가 이미 적용된 경우에는 새로 적용할
    // 필요가 없습니다.  메시징 서비스만 이용하는 경우 참조해주세요.
    // =======================================================
    // SDK 호출
    DOT.initialization(this)

    // =======================================================
    // Start : Push 메시지 수신을 위한 설정 <-- 새로 추가된 부분
    // =======================================================
    FirebaseMessaging.getInstance().getToken()
      .addOnCompleteListener(OnCompleteListener<String?> { task ->
        if (!task.isSuccessful) {
          Log.w("FCM", "Fetching FCM registration token failed", task.exception)
          return@OnCompleteListener
        }

        // Get new FCM registration token
        val token = task.result

        // Log and toast
        DOT.setPushToken(token)
      })
    // =======================================================
    // End : Push 메시지 수신을 위한 설정
    // =======================================================
    ...
  }
  ...
}
```

{% endtab %}
{% endtabs %}

`FirebaseMessagingService`를 상속받은 `FcmService.java` 파일을 새로 생성하고 푸시 토큰을 수집하도록 아래와 같이 설정합니다.

`FcmService`

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

```java
import com.google.firebase.messaging.FirebaseMessagingService;
import com.sdk.wisetracker.new_dot.open.DOT;

public class FcmService extends FirebaseMessagingService {
    // =======================================================
    // Start : Push 토큰 수집 <-- 새로 추가된 부분
    // =======================================================
    @Override
    public void onNewToken(String token) {
        super.onNewToken(token);
        // call Wisetracker API
        DOT.setPushToken(token);
    }
    // =======================================================
    // End : Push 토큰 수집
    // =======================================================
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
import com.google.firebase.messaging.FirebaseMessagingService
import com.sdk.wisetracker.new_dot.open.DOT

class FcmService : FirebaseMessagingService() {
  // =======================================================
  // Start : Push 토큰 수집 <-- 새로 추가된 부분
  // =======================================================
  override fun onNewToken(token: String) {
    super.onNewToken(token)
    // call Wisetracker API
    DOT.setPushToken(token)
  }
  // =======================================================
  // End : Push 토큰 수집
  // =======================================================
}
```

{% endtab %}
{% endtabs %}

#### **`AndroidManifest`**

1. `FcmService.java` 파일을 서비스로 등록합니다.
2. 푸시 알림 권한을 선언합니다.

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

```markup
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.support.wisetracker">
    
    <!--
      // ==================================================
      // Wisetracker SDK Push: 푸시 알림 권한을 선언합니다. <-- 새로 추가된 부분
      // ==================================================
    -->
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

  <application
      ...>
    ...
    <!--
      // ==================================================
      // Start : SDK FCM 서비스 적용 <-- 새로 추가된 부분
      // ==================================================
    -->
    <service
        android:name=".FcmService"
        android:exported="false">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>
    <!--
      // ==================================================
      // End : SDK FCM 서비스 적용
      // ==================================================
    -->
    ...
  </application>

</manifest>
```

{% endtab %}
{% endtabs %}

### 푸시메시지 클릭 측정

푸시 메시지를 클릭하는 것을 측정하기 위해 푸시 메시지를 통해 진입하는 최초`Activity`에 `setPushClick`을 추가합니다.

아래 MainActivity 에 해당하는 Activity 는 "AndroidManifest.xml"에 아래와 같이 Main action 으로 지정된 Activity에 적용되어야 합니다. 대부분의 경우, MainActivity 이나 앱 개발에 따라 다릅니다.

#### **`MainActivity`**

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

```java
public class MainActivity extends AppCompatActivity {
  ...
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    // =======================================================
    // 이 내용은 Wisetracker 기본 SDK가 이미 적용된 경우에는 새로 적용할
    // 필요가 없습니다.  메시징 서비스만 이용하는 경우 참조해주세요.
    // =======================================================
    // SDK 호출
    DOT.initialization(this);

    // =======================================================
    // Start : Push 메시지 수신을 위한 설정
    // =======================================================
    FirebaseMessaging.getInstance().getToken()
        .addOnCompleteListener(new OnCompleteListener<String>() {
          @Override
          public void onComplete(@NonNull Task<String> task) {
            if (!task.isSuccessful()) {
              Log.w("FCM", "Fetching FCM registration token failed", task.getException());
              return;
            }
            // Get new FCM registration token
            String token = task.getResult();
            // 푸시 토큰 서버 전송
            DOT.setPushToken(token);
          }
        });
    // =======================================================
    // End : Push 메시지 수신을 위한 설정
    // =======================================================

    // =======================================================
    // Start : Push 메시지 클릭 처리 <-- 새로 추가된 부분 (1/2)
    // =======================================================
    DOT.setPushClick(this, getIntent());
    // =======================================================
    // End : Push 메시지 클릭 처리
    // =======================================================
    ...
  }
  ...
  
  // =======================================================
  // Start : Push 메시지 클릭 처리 <-- 새로 추가된 부분 (2/2)
  // =======================================================
  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // 푸시 메시지를 클릭할 때의 처리
    DOT.setPushClick(this, intent);
    ...
  }
  // =======================================================
  // End : Push 메시지 클릭 처리
  // =======================================================
  ...
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    ...
    // =======================================================
    // 이 내용은 Wisetracker 기본 SDK가 이미 적용된 경우에는 새로 적용할
    // 필요가 없습니다.  메시징 서비스만 이용하는 경우 참조해주세요.
    // =======================================================
    // SDK 호출
    DOT.initialization(this)

    // =======================================================
    // Start : Push 메시지 수신을 위한 설정
    // =======================================================
    FirebaseMessaging.getInstance().getToken()
      .addOnCompleteListener(OnCompleteListener<String?> { task ->
        if (!task.isSuccessful) {
          Log.w("FCM", "Fetching FCM registration token failed", task.exception)
          return@OnCompleteListener
        }

        // Get new FCM registration token
        val token = task.result

        // Log and toast
        DOT.setPushToken(token)
      })
    // =======================================================
    // End : Push 메시지 수신을 위한 설정
    // =======================================================

    // =======================================================
    // Start : Push 메시지 클릭 처리 <-- 새로 추가된 부분 (1/2)
    // =======================================================
    DOT.setPushClick(this, intent)
    // =======================================================
    // End : Push 메시지 클릭 처리
    // =======================================================
    ...
  }
  ...

  // =======================================================
  // Start : Push 메시지 클릭 처리 <-- 새로 추가된 부분 (2/2)
  // =======================================================
  override fun onNewIntent(intent: Intent) {
    super.onNewIntent(intent)
    // 푸시 메시지를 클릭할 때의 처리
    DOT.setPushClick(this, intent)
  }
  // =======================================================
  // End : Push 메시지 클릭 처리
  // =======================================================
  ...
}
```

{% endtab %}
{% endtabs %}

### 푸시 수신동의

푸시발송은 기본 적용에서는 "수신거부"입니다. 아래 링크를 참조하여 화면에서 수신동의/거부를 진행 후 해당 데이터를 "태깅"작업을 통해 남겨주세요.

{% embed url="<https://document.wisetracker.co.kr/v2-developer/in-app-event/event-list/messaging#push_noti_authorized>" %}

## 축하합니다 🎉

이제 Android SDK 설정이 완료되었습니다.


---

# Agent Instructions: 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:

```
GET https://document.wisetracker.co.kr/v2-developer/push/undefined/android/pushsdksetting.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
