메세지를 하나의 디바이스에서 다른 디바이스로 보내는 방법입니다.
일단은 서버키를 넣어주고

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Constants { | |
companion object { | |
const val BASE_URL = "https://fcm.googleapis.com" | |
const val SERVER_KEY = "토큰키" | |
const val CONTENT_TYPE = "application/json" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface NotificationAPI { | |
@Headers("Authorization: key=$SERVER_KEY", "Content-Type:$CONTENT_TYPE") | |
@POST("fcm/send") | |
suspend fun postNotification( | |
@Body notification: PushNotification | |
): Response<ResponseBody> | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data class NotificationData( | |
val title: String, | |
val message: String | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data class PushNotification( | |
val data: NotificationData, | |
val to: String | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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에서 권한 추가

'Android(Kotlin)' 카테고리의 다른 글
task 'assembledebug' not found in project ' app'. android studio (2) | 2021.02.25 |
---|---|
Android Kotlin ViewModel LiveData (0) | 2021.02.18 |
Android Workmanager (0) | 2021.02.15 |
Android Foreground Service (0) | 2021.02.12 |
Android Image Upload from gallary (0) | 2021.02.05 |