9
6

More than 3 years have passed since last update.

Firebase Cloud Messagingでトークンの取得方法が変わっていた

Posted at

タイトルのとおり。
com.google.firebase:firebase-messaging.20.3.0 からは FirebaseInstanceId クラスの getInstanceId 関数からではなく、FirebaseMessaging クラスの getToken 関数から取得するようになったようだ。

// 1. リスナーで非同期的に取得するやり方
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
    if (!task.isSuccessful) {
        return@OnCompleteListener
    }

    val token = task.result
}

// 2. kotlinx-coroutines-play-servicesを使ってコルーチン内で同期的に取得するやり方
val token = FirebaseMessaging.getInstance().token.await()

参考:com.google.firebase:firebase-messaging.20.3.0より前の書き方( deprecated

// 1. リスナーで非同期的に取得するやり方
FirebaseInstanceId.getInstance().instanceId.addOnCompleteListener { task ->
    if (!task.isSuccessful) {
        return@addOnCompleteListener
    }

    val token = task.result?.token
}

// 2. kotlinx-coroutines-play-servicesを使ってコルーチン内で同期的に取得するやり方
val token = FirebaseInstanceId.getInstance().instanceId.await().token

「親クラス(FirebaseInstanceId)が持つinstanceId、の中にあるtoken」から「親クラス(FirebaseMessaging)が持つtoken」に変わっているのがハマりポイントかも。

9
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6