> For the complete documentation index, see [llms.txt](https://platform-business.gitbook.io/klat/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://platform-business.gitbook.io/klat/android/push-notification.md). Agents can also search and read this documentation through its [MCP server](https://platform-business.gitbook.io/klat/~gitbook/mcp).

# Push Notification

### Enable / Disable Push Notification

사용자가 Push Notification을 받을 지 여부를 설정할 수 있습니다.

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

```java
// 사용자 Push Notification 활성화
TalkPlus.enablePushNotification(new TalkPlus.CallbackListener<TPUser>() {
    @Override
    public void onSuccess(TPUser tpUser) {
    }
    @Override
    public void onFailure(int i, Exception e) {
    }
});

// 사용자 Push Notification 비활성화
TalkPlus.disablePushNotification(new TalkPlus.CallbackListener<TPUser>() {
    @Override
    public void onSuccess(TPUser tpUser) {
    }
    @Override
    public void onFailure(int i, Exception e) {
    }
});
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
// 사용자 Push Notification 활성화
TalkPlus.enablePushNotification(object : TalkPlus.CallbackListener<TPUser>() {
    override fun onSuccess(tpUser: TPUser) { }
    override fun onFailure(i: Int, e: Exception) { }
}

// 사용자 Push Notification 비활성화
TalkPlus.disablePushNotification(object : TalkPlus.CallbackListener<TPUser>() {
    override fun onSuccess(tpUser: TPUser) { }
    override fun onFailure(i: Int, e: Exception) { }
})
```

{% endtab %}
{% endtabs %}

특정 채널의 Push Notification을 받을 지 여부를 설정할 수 있습니다.

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

```java
// 채널 Push Notification 활성화
TalkPlus.enableChannelPushNotification(String channel, new TalkPlus.CallbackListener<TPUser>() {
    @Override
    public void onSuccess(TPUser tpUser) {
    }
    @Override
    public void onFailure(int i, Exception e) {
    }
});

// 채널 Push Notification 비활성화
TalkPlus.disableChannelPushNotification(String channel, new TalkPlus.CallbackListener<TPUser>() {
    @Override
    public void onSuccess(TPUser tpUser) {
    }
    @Override
    public void onFailure(int i, Exception e) {
    }
});
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
// 채널 Push Notification 활성화
TalkPlus.enableChannelPushNotification(channel: String, object : TalkPlus.CallbackListener<TPUser>() {
    override fun onSuccess(tpUser: TPUser) { }
    override fun onFailure(i: Int, e: Exception) { }
}

// 채널 Push Notification 비활성화
TalkPlus.disableChannelPushNotification(channel: String, object : TalkPlus.CallbackListener<TPUser>() {
    override fun onSuccess(tpUser: TPUser) { }
    override fun onFailure(i: Int, e: Exception) { }
})
```

{% endtab %}
{% endtabs %}

### Push Notification

TalkPlus의 Push Notification은 FCM을 통하여 이루어지게 됩니다. 기본적인 FCM을 연동하신 후, User를 로그인한 후 `registerFCMToken` 함수를 호출하여 FCM 토큰을 User 세션에 연동하여야 합니다.

로그인이 완료된 후 아래와 같이 `FirebaseMessaging`을 통하여 token을 얻어 register 하시는 것을 권장 드립니다.

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

```kotlin
// 푸시 권한 요청 (안드로이드 13이상 API 33)
private ActivityResultLauncher<String> requestPermissionLauncher =
    registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
        if (isGranted) {
            // 권한이 허용됨
        } else {
            // 권한이 거부됨
        }
    });

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    if (ContextCompat.checkSelfPermission(
            this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
        // 권한이 이미 허용됨
    } else if (shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)) {
        // 사용자에게 권한 필요성 설명
        // 권한을 요청
        requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS);
    } else {
        // 권한 요청
        requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS);
    }
}

// Firebase Messaging을 통하여 현재 token을 획득
public void getFCMToken() {
    FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
    @Override
    public void onComplete(@NonNull com.google.android.gms.tasks.Task<String> task) {
        if (!task.isSuccessful()) {
            return;
        }
        String fcmToken = task.getResult();
        // 토큰 등록
        TalkPlus.registerFCMToken(fcmToken, new CallbackListener<Void>() {
            @Override
            public void onSuccess(Void result) { }

            @Override
            public void onFailure(int errorCode, Exception exception) { }
        });
      }
  });
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
// 푸시 권한 요청 (안드로이드 13이상 API 33)
private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        if (isGranted) {
            // 권한이 허용됨
        } else {
            // 권한이 거부됨
        }
    }

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    when {
        ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.POST_NOTIFICATIONS
        ) == PackageManager.PERMISSION_GRANTED -> {
            // 권한이 이미 허용됨
        }
        
        shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS) -> {
            // 사용자에게 권한 필요성 설명
            // 권한을 요청
            requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
        }
        
        else -> {
            // 권한 요청
            requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
        }
    }
}

// Firebase Messaging을 통하여 현재 token을 획득
fun getFCMToken() {
    FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
        if (!task.isSuccessful) {
            return@OnCompleteListener
        }
        val fcmToken: String = task.result
        // 토큰 등록
        TalkPlus.registerFCMToken(fcmToken, object : CallbackListener<Void?> {
            override fun onSuccess(t: Void?) { }
            override fun onFailure(errorCode: Int, exception: Exception) { }
        })
        return@OnCompleteListener
    })
}
```

{% endtab %}
{% endtabs %}

이후 아래와 같이 `onMessageReceived`에 TalkPlus에서 제공하는 `processFirebaseCloudMessagingData` 함수를 호출하는 코드를 삽입하여 Push Notification을 처리할 수 있습니다.

Foreground인 경우 기존에 등록되어있는 `ChannelListener`를 통하여 자동으로 콜백을 올리게 됩니다.

Background인 경우 앱이 실행되어있지 않은 상태라 등록된 콜백이 없을 수 있으므로 아래와 같이 1회용 콜백을 함께 등록하여 이벤트를 받아 원하는 동작을 수행하실 수 있습니다.

`processFirebaseCloudMessagingData` 함수에서 마지막 인자값으로 `forceCallback`을 `boolean` 으로 받게 되어 있는데, `forceCallback`은 실시간 채널에서 콜백 수신과 상관없이 FCM 통해 무조건 콜백을 받아 처리하기 위해서는 `true`로 넘겨주셔야 합니다.

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

```java
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage.getData().containsKey("talkplus")) {
        try {
            // channelId, title, body 정보가 필요한 경우 아래와 같이 사용합니다.
            JSONObject talkplus = new JSONObject(
                remoteMessage.getData().get("talkplus")
            );
            String channelId = talkplus.getString("channelId");
            String messageId = talkplus.getString("messageId"); // available only for message event
            String title = talkplus.getString("title");
            String body = talkplus.getString("body");
        } catch (JSONException e) {
        }
    
        if (isBackground) {
            TalkPlus.processFirebaseCloudMessagingData(
                remoteMessage.getData(), 
                new TalkPlus.ChannelListener() {
                    // TODO: 각 서비스의 시나리오에 맞춰 Push Notification 표시
                    @Override
                    public void onMemberAdded(TPChannel channel, List<TPUser> users) {
                    }
                    @Override
                    public void onMemberLeft(TPChannel channel, List<TPUser> users) {
                    }
                    @Override
                    public void onMessageReceived(TPChannel channel, TPMessage message) {
                    }
                    @Override
                    public void onChannelChanged(TPChannel channel) {
                    }
                }, 
                true
            );
        } else {
            TalkPlus.processFirebaseCloudMessagingData(remoteMessage.getData(), true);
        }
    }
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
override fun onMessageReceived(remoteMessage: RemoteMessage) {
    remoteMessage.data["talkplus"]?.let {
        try {
            // channelId, title, body 정보가 필요한 경우 아래와 같이 사용합니다.
            val talkplus = JSONObject(it)
            val channelId = talkplus.getString("channelId")
            val messageId = talkplus.getString("messageId") // available only for message event
            val title = talkplus.getString("title")
            val body = talkplus.getString("body")
        } catch (e: JSONException) {
            
        }

        if (isBackground()) {
            TalkPlus.processFirebaseCloudMessagingData(
                remoteMessage.data,
                object : TalkPlus.ChannelListener {
                    // TODO: 각 서비스의 시나리오에 맞춰 Push Notification 표시
                    override fun onMemberAdded(channel: TPChannel, users: List<TPUser>) { }

                    override fun onMemberLeft(channel: TPChannel, users: List<TPUser>) { }

                    override fun onMessageReceived(channel: TPChannel, message: TPMessage) { }

                    override fun onChannelChanged(channel: TPChannel) { }
                },
                true
            )
        } else {
            TalkPlus.processFirebaseCloudMessagingData(remoteMessage.data, true)
        }
    }
}
```

{% endtab %}
{% endtabs %}

포그라운드와 백그라운드 모두 동일하게 `onMessageReceived`를 통해 개발자가 원하는대로 컨트롤 하려면 Data타입의 푸쉬를 받아야 합니다. 대시보드에 다음과 같이 설정해야 data 타입 푸쉬를 받게 됩니다.

* 전체 Push Notification 설정 활성화

<figure><img src="https://3266115823-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FlHh876RsPWbL2TFBBUGX%2Fuploads%2Fgit-blob-2cf1b918fbd31f873081f4e6812aa98cfde99d8d%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

* AOS "메시지 수신 알림" 비활성화

<figure><img src="https://3266115823-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FlHh876RsPWbL2TFBBUGX%2Fuploads%2Fgit-blob-d6e1b9b823c1ded5f1f2d6e009765e5653c884d0%2Fimage%20(2).png?alt=media" alt=""><figcaption></figcaption></figure>
