> ## Documentation Index
> Fetch the complete documentation index at: https://docs.notifly.tech/llms.txt
> Use this file to discover all available pages before exploring further.

# Android

> Notifly Android SDKのインストール、初期化、プッシュ通知とアプリ内ポップアップの連携方法を説明します。

Notifly Android SDKは、AndroidアプリにNotiflyを組み込むためのSDKです。\
次の機能に対応しています。

* デバイス情報をNotiflyに登録し、プッシュ通知を受信したり、アプリ内ポップアップを表示したりできます。
  （アプリ内ポップアップは、アプリがフォアグラウンドのときにのみ表示されます。）
* イベントとユーザー情報をNotiflyに送信し、キャンペーンのターゲティングと分析に使用できます。
* ユーザー行動をイベントとして記録し、キャンペーンの効果を測定できます。

## 事前準備

1. **Firebaseプロジェクトを連携します。**\
   Notifly Android SDKは、プッシュ通知の送信に[Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging)を使用します。

> [Firebaseプロジェクトの連携ガイド](https://docs.notifly.tech/ja/developer-guide/firebase-integration.md)

2. **アプリ内ポップアップにはAndroid 11（APIレベル30）以降が必要です。**\
   アプリ内ポップアップキャンペーンは、Android 11以降でのみ利用できます。

***

## 1. SDKのインストール

Notifly Android SDKは、[JitPack](https://jitpack.io/)で配布されています。

### Gradleの設定

> [tab] Gradle 7.0以降
>
> ```gradle title="settings.gradle" highlight={3} theme={null}
> dependencyResolutionManagement {
>     repositories {
>         maven { url 'https://jitpack.io' }
>     }
> }
> ```

> [tab] Gradle 7.0より前
>
> ```gradle title="build.gradle (root)" highlight={4} theme={null}
> allprojects {
>     repositories {
>         ...
>         maven { url 'https://jitpack.io' }
>     }
> }
> ```

### SDKの依存関係の追加

```gradle title="build.gradle (Module: app)" theme={null}
dependencies {
    implementation 'com.github.team-michael:notifly-android-sdk:1.12.0'
}
```

> [!NOTE]
>
> SDKの機能更新とセキュリティ更新は随時公開されます。[JitPackの最新バージョン](https://jitpack.io/#team-michael/notifly-android-sdk)を使用してください。

### SDKの初期化

SDKは`Application`クラスで初期化することを推奨します。特定のActivityで初期化すると、ほかのActivityでは初期化が適用されない場合があります。

> [!NOTE]
>
> **Applicationクラスがない場合**は、\
> クラスを作成し、`AndroidManifest.xml`の`android:name`属性に登録してください。

```xml title="AndroidManifest.xml" highlight={4} theme={null}
<!-- Applicationクラスを登録します。 -->
<application
    ...
    android:name=".MainApplication"
    ... >
</application>
```

> [tab] Kotlin
>
> アプリのApplicationクラスの`onCreate`に、次のコードを追加します。
>
> ```kotlin title="MainApplication.kt" highlight={6-11} theme={null}
> import tech.notifly.Notifly
>
> class MainApplication : Application() {
>     override fun onCreate() {
>         super.onCreate()
>         Notifly.initialize(
>             applicationContext,
>             NOTIFLY_PROJECT_ID,
>             BuildConfig.NOTIFLY_USERNAME,
>             // passwordは後方互換性のためのプレースホルダーです。実際のパスワードやAPI Secret Keyを指定しないでください。
>             BuildConfig.NOTIFLY_USERNAME
>         )
>     }
> }
> ```

> [tab] Java
>
> アプリのApplicationクラスの`onCreate`に、次のコードを追加します。
>
> ```java title="MainApplication.java" highlight={8-13} theme={null}
> import tech.notifly.Notifly;
>
> public class MainApplication extends Application {
>     @Override
>     public void onCreate() {
>         super.onCreate();
>         ...
>         Notifly.initialize(
>             this,
>             NOTIFLY_PROJECT_ID,
>             BuildConfig.NOTIFLY_USERNAME,
>             // passwordは後方互換性のためのプレースホルダーです。実際のパスワードやAPI Secret Keyを指定しないでください。
>             BuildConfig.NOTIFLY_USERNAME
>         );
>         ...
>     }
> }
> ```

> [!NOTE]
>
> `NOTIFLY_PROJECT_ID`と`USERNAME`は設定ページで確認できます。`PASSWORD`は後方互換性のためのプレースホルダーです。`USERNAME`と同じ空でない値を渡してください。実際のパスワードやAPI Secret Keyは指定しないでください。

***

## 2. ユーザー情報の登録

Notiflyは、ユーザー識別子（`userId`）とユーザー属性（`params`）を使って、マーケティングキャンペーンをパーソナライズします。\
登録したユーザー情報は、**セグメントの分類や、プッシュ通知、メール、カカオアリムトークなどの配信対象の設定**に使用されます。

> [!NOTE]
>
> ユーザー情報の登録メソッドは、`Notifly.initialize()`によるSDKの初期化が完了してから呼び出してください。

### ユーザーIDの登録（`Notifly.setUserId()`）

```kotlin theme={null}
Notifly.setUserId(context: Context, userId: String?)
```

`userId`には、アプリ内でログインしているユーザーの識別子を設定します。\
Notiflyは、この値を使ってユーザーのイベントを追跡し、キャンペーンをパーソナライズします。

**context** `Context` *required*

AndroidのContextオブジェクトです。

**userId** `String` *required*

ログインしているユーザーのIDです。ログアウト時に`null`を渡すと、関連付けが解除されます。

#### ユーザーIDの解除

ログアウト時には、`setUserId(null)`を呼び出して、現在のデバイスとユーザーの関連付けを解除することを推奨します。
同じユーザーデータを保持する必要がある場合は、サーバーまたはアプリ内で別途管理してください。

> [tab] Kotlin
>
> ```kotlin title="setUserId" theme={null}
> import tech.notifly.Notifly
>
> // ログイン時。
> Notifly.setUserId(context, "user_12345")
>
> // ログアウト時。
> Notifly.setUserId(context, null)
> ```

> [tab] Java
>
> ```java title="setUserId" theme={null}
> import tech.notifly.Notifly;
>
> Context context = getApplicationContext();
>
> // ログイン時。
> Notifly.setUserId(context, "user_12345");
>
> // ログアウト時。
> Notifly.setUserId(context, null);
> ```

### ユーザー属性の登録（`Notifly.setUserProperties()`）

`setUserProperties`で、ユーザーの属性情報を登録します。\
登録した情報は、**セグメントのターゲティング**、**メッセージのパーソナライズ**、**配信チャネルの選択**などに使用されます。

> [!NOTE]
>
> **機密性の高いユーザー属性を送信する前に**
>
> 氏名や住所など、保護が必要なカスタムユーザー属性を送信する前に、コンソールの**ユーザー管理** > **ユーザー一覧**の**属性管理**で、送信するキーと同じ名前の属性を登録し、暗号化を有効にしてください。
>
> 設定方法と利用上の制約については、[属性管理ガイド](https://docs.notifly.tech/ja/user-guide/users/properties.md)を確認してください。

```kotlin theme={null}
Notifly.setUserProperties(context: Context, params: Map<String, Any?>)
```

**context** `Context` *required*

AndroidのContextオブジェクトです。

**params** `Map\<String, Any?\>` *required*

ユーザー属性のキーと値のペアです。`$email`、`$phone_number`、`$line_user_id`などの定義済みキーを使用できます。

> [!NOTE]
>
> * `$email`: メールキャンペーンに使用するメールアドレスです。
> * `$phone_number`: SMSやカカオのキャンペーンに使用する電話番号です。
> * `$line_user_id`: LINEメッセージキャンペーンに使用するLINEユーザーIDです。
> * カスタムフィールド: `"plan"`、`"tier"`、`"country"`など、任意のフィールドを設定できます。

> [tab] Kotlin
>
> ```kotlin title="setUserProperties" theme={null}
> import tech.notifly.Notifly
>
> // メールアドレス、電話番号、プランを登録します。
> Notifly.setUserProperties(
>     context,
>     mapOf(
>         "\$email" to "user@example.com",
>         "\$phone_number" to "01012345678",
>         "plan" to "premium",
>         "language" to "ko"
>     )
> )
> ```

> [tab] Java
>
> ```java title="setUserProperties" theme={null}
> import tech.notifly.Notifly;
>
> Context context = getActivity();
>
> HashMap<String, Object> userProperties = new HashMap<>();
> userProperties.put("$email", "user@example.com");        // メールキャンペーン。
> userProperties.put("$phone_number", "01012345678");      // SMS / KakaoTalk。
> userProperties.put("membership_tier", "gold");           // セグメント分類用のカスタムフィールド。
>
> Notifly.setUserProperties(context, userProperties);
> ```

***

## 3. イベントの記録（`Notifly.trackEvent()`）

ユーザー行動を記録すると、**キャンペーンのトリガー**、**セグメントの条件**、**効果分析**などに使用できます。\
ボタンのクリック、ページへのアクセス、購入完了などのユーザー行動をイベントとして収集します。

```kotlin theme={null}
Notifly.trackEvent(
    context: Context,
    eventName: String,
    eventParams: Map<String, Any?> = emptyMap(),
    segmentationEventParamKeys: List<String>? = null,
)
```

**context** `Context` *required*

AndroidのContextオブジェクトです。

**eventName** `String` *required*

イベント名です。たとえば、`"click_button"`や`"purchase_completed"`を指定します。

**eventParams** `Map\<String, Any?\>`

イベントに付加するパラメーターです。たとえば、`"plan": "premium"`や`"duration": 120`を指定できます。

**segmentationEventParamKeys** `List\<String\>`

セグメントの分類に使用するイベントパラメーターキーのリストです。指定できるキーは最大1つです。

> [!NOTE]
>
> `segmentationEventParamKeys`に指定できるキーは、現在**最大1つ**です。
>
> * 例として、`listOf("plan")`を指定すると、`"plan"`イベントパラメーターをセグメントの分類に使用できます。

> [tab] Kotlin（Jetpack Compose）
>
> ```kotlin title="Notifly.trackEvent" highlight={5-13} theme={null}
> import tech.notifly.Notifly
> ...
> Button(
>     onClick = {
>         Notifly.trackEvent(
>             context,
>             "click_button_1",
>             mapOf(
>                 "signup_method" to "kakao",
>                 "purchased" to "true",
>                 "duration" to 45,
>             ),
>             listOf("signup_method") // signup_methodをセグメントの分類キーに指定します。
>         )
>     },
>     modifier = Modifier.padding(top = 16.dp)
> ) {
>     Text(text = "click_button_1")
> }
> ...
> ```

> [tab] Kotlin（XMLレイアウト）
>
> ```kotlin title="Notifly.trackEvent" highlight={3-34} theme={null}
> import tech.notifly.Notifly
> ...
> val button = findViewById<Button>(R.id.button)
>
> // ラムダ式を使用する場合。
> button.setOnClickListener {
>     Notifly.trackEvent(
>         context,
>         "click_button_1",
>         mapOf(
>             "signup_method" to "kakao",
>             "purchased" to "true",
>             "duration" to 45,
>         ),
>         listOf("signup_method") // signup_methodをセグメントの分類キーに指定します。
>     )
> }
>
> // ラムダ式を使用しない場合。
> button.setOnClickListener(object : View.OnClickListener {
>     override fun onClick(v: View) {
>         Notifly.trackEvent(
>             context,
>             "click_button_1",
>             mapOf(
>                 "signup_method" to "kakao",
>                 "purchased" to "true",
>                 "duration" to 45,
>             ),
>             listOf("signup_method") // signup_methodをセグメントの分類キーに指定します。
>         )
>     }
> })
> ...
> ```

> [tab] Java
>
> ```java title="Notifly.trackEvent" highlight={8-20} theme={null}
> import tech.notifly.Notifly;
>
> HashMap<String, Object> map = new HashMap<>();
> map.put("signup_method", "kakao");
> map.put("purchased", true);
> map.put("duration", 45);
>
> // セグメントの分類キーのリストを作成します。
> List<String> segmentationEventParamKeys = Arrays.asList("signup_method");
>
> Button button = findViewById(R.id.button);
>
> // ラムダ式を使用する場合。
> button.setOnClickListener(v -> {
>     Notifly.trackEvent(context, "click_button_1", map, segmentationEventParamKeys);
> });
>
> // ラムダ式を使用しない場合。
> button.setOnClickListener(new View.OnClickListener() {
>     public void onClick(View v) {
>         Notifly.trackEvent(context, "click_button_1", map, segmentationEventParamKeys);
>     }
> });
> ```

***

## 4. 内部ユーザーIDの取得

`getNotiflyUserId()`は、Notiflyが内部で管理する一意のユーザーIDを返します。\
このIDは、`setUserId()`で登録するユーザーIDとは**別の識別子**です。通常の連携では使用する必要はありません。\
外部CRMやサードパーティーサービスとの連携で、Notiflyの内部ユーザーIDが必要な場合に使用します。

```kotlin theme={null}
Notifly.getNotiflyUserId(context)
```

***

## 5. 連携テスト

SDKのインストール後、連携テストガイドに沿って、イベントの収集とプッシュ通知の受信を確認してください。\
[連携をテストする](https://docs.notifly.tech/ja/integration-test.md)

***

## 6. 高度な連携

> [card] [プッシュ通知アイコンの設定](https://docs.notifly.tech/ja/advanced/push-notification-icon.md)

> [card] [プッシュ通知の許可をリクエストする](https://docs.notifly.tech/ja/advanced/push-notification-consent.md)

> [card] [プッシュ通知のクリックイベント](https://docs.notifly.tech/ja/advanced/push-notification-click-events.md)

> [card] [プッシュ通知インターセプター](https://docs.notifly.tech/ja/advanced/push-notification-interceptor.md)

> [card] [アプリ内ポップアップのイベントリスナー](https://docs.notifly.tech/ja/advanced/inapp-popup-event-listener.md)

> [card] [WebView](https://docs.notifly.tech/ja/advanced/webview.md)

***

## FAQ

> [accordion] すでにFirebase Cloud Messagingを使用している場合はどうすればよいですか？
>
> Notifly Android SDKは、アプリで使用中のFirebase Cloud Messagingと併用できます。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.