Android(Kotlin)

Android FCM message | one device to another device

----___<<<<< 2021. 2. 16. 03:44

 메세지를 하나의 디바이스에서 다른 디바이스로 보내는 방법입니다.

 

 

 

 

 일단은 서버키를 넣어주고

 

 

class Constants {
companion object {
const val BASE_URL = "https://fcm.googleapis.com"
const val SERVER_KEY = "토큰키"
const val CONTENT_TYPE = "application/json"
}
}
view raw Constants.kt hosted with ❤ by GitHub
private const val CHANNEL_ID = "my_channel"
class FirebaseService : FirebaseMessagingService() {
companion object {
var sharedPref: SharedPreferences? = null
var token: String?
get() {
return sharedPref?.getString("token", "")
}
set(value) {
sharedPref?.edit()?.putString("token", value)?.apply()
}
}
override fun onNewToken(newToken: String) {
super.onNewToken(newToken)
token = newToken
}
override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
val intent = Intent(this, MainActivity::class.java)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationID = Random.nextInt()
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel(notificationManager)
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, FLAG_ONE_SHOT)
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(message.data["title"])
.setContentText(message.data["message"])
.setSmallIcon(R.drawable.ic_launcher_background)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.build()
notificationManager.notify(notificationID, notification)
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(notificationManager: NotificationManager) {
val channelName = "channelName"
val channel = NotificationChannel(CHANNEL_ID, channelName, IMPORTANCE_HIGH).apply {
description = "My channel description"
enableLights(true)
lightColor = Color.GREEN
}
notificationManager.createNotificationChannel(channel)
}
}
const val TOPIC = "/topics/myTopic2"
class MainActivity : AppCompatActivity() {
val TAG = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
FirebaseService.sharedPref = getSharedPreferences("sharedPref", Context.MODE_PRIVATE)
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener {
FirebaseService.token = it.token
etToken.setText(it.token)
Log.e("MainActivity", it.token)
}
FirebaseMessaging.getInstance().subscribeToTopic(TOPIC)
btnSend.setOnClickListener {
val title = etTitle.text.toString()
val message = etMessage.text.toString()
val recipientToken = etToken.text.toString()
if(title.isNotEmpty() && message.isNotEmpty() && recipientToken.isNotEmpty()) {
PushNotification(
NotificationData(title, message),
recipientToken
).also {
sendNotification(it)
}
}
}
}
private fun sendNotification(notification: PushNotification) = CoroutineScope(Dispatchers.IO).launch {
try {
val response = RetrofitInstance.api.postNotification(notification)
if(response.isSuccessful) {
Log.d(TAG, "Response: ${Gson().toJson(response)}")
} else {
Log.e(TAG, response.errorBody().toString())
}
} catch(e: Exception) {
Log.e(TAG, e.toString())
}
}
}
view raw MainActivity.kt hosted with ❤ by GitHub
interface NotificationAPI {
@Headers("Authorization: key=$SERVER_KEY", "Content-Type:$CONTENT_TYPE")
@POST("fcm/send")
suspend fun postNotification(
@Body notification: PushNotification
): Response<ResponseBody>
}
data class NotificationData(
val title: String,
val message: String
)
data class PushNotification(
val data: NotificationData,
val to: String
)
class RetrofitInstance {
companion object {
private val retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val api by lazy {
retrofit.create(NotificationAPI::class.java)
}
}
}

 

 그리고 manifest에서 권한 추가