1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Firebase Cloud MessagingをAndroid端末間で送受信する方法

Last updated at Posted at 2021-07-10

趣味でAndroidアプリの開発をしていますが、端末間で通知の送受信を行う方法が調べても出てこなかったので記録として残しておきます。
HTTP通信で通知内容をJSON形式で送る手法を用いています。

初学者なので所々間違っているかもしれません。ご了承ください。


private val URL = "https://fcm.googleapis.com/fcm/send"
private val MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8") 
private val CLIENT = OkHttpClient()
private val id = "送信者ID"

Thread{//非同期処理じゃないと動かないので注意
  try {
      val jsonData = "{\"to\":\"見守る側の端末トークン}\",\"notification\":{\"title\":\"通知のタイトル\",\"body\":\"通知の詳細\"}}"
      val serverKey = "サーバキー"
      send(serverKey,jsonData)
  }catch (e:Exception){
      エラーメッセージ
  }
}.start()

private fun send(serverKey: String, jsonString: String): Response = newCall(serverKey, jsonString).execute()

private fun newCall(serverKey: String, jsonString: String): Call =
    CLIENT.newCall(
        Request.Builder()
        .url(URL)
        .header("Authorization", "key=$serverKey")
        .header("project_id","key=$id")
        .post(RequestBody.create(MEDIA_TYPE_JSON, jsonString))
        .build()
    )

これで一応動きました。
サーバキーと送信者IDはFirebaseコンソール上で、トークンはRealtime Databaseに事前に登録しているものを使用しています。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?