자 어제에 이어서 2편을 써 보도록 하겠습니다 .
일단 다시 Firebase 홈페이지로 다시 가보도록 하겠습니다 .
화면 중앙에 나타나는 자신의 프로젝트를 클릭해주시고 ~ 그 다음에 Authentication 클릭 !
그 뒤에 Sign in method 를 클릭하셔서 제공업체를 추가해주셔야 됩니다 .
저같은 경우는 google로 하였습니다 .
이제 다시 안드로이드로 돌아와서 일단 class 를 하나 만들어 줍니다 . 저는 Constants 라고 지정하였습니다.
class Constants {
companion object {
const val BASE_URL = "https://fcm.googleapis.com"
const val SERVER_KEY = "자신의 서버키 "
const val CONTENT_TYPE = "application/json"
}
}
여기서 서버키가 뭐야? 라고 생각을 하실겁니다 . 서버키는 어디서 찾을수있냐면
다시 Firebase 홈페이지 - 프로젝트 클릭 - 자신이 등록한 앱 클릭해서 들어갑니다 .
그 뒤에 상단에 있는 클라우드 메시징 탭에 들어가면 자신의 서버키를 확인할 수 있습니다 . 그거 복사해서
안드로이드에 붙여 넣어주세요~
이제 60 % 오셨습니다.
안드로이드 가셔서 interface 를 만들어줍니다 . NotificationAPI로 칭했습니다.
interface NotificationAPI {
@Headers("Authorization: key=$SERVER_KEY", "Content-Type:$CONTENT_TYPE")
@POST("fcm/send")
suspend fun postNotification(
@Body notification: PushNotification
): Response<ResponseBody>
}
그리고 class를 RetrofitInstance 하나 더 만들어 줍니다 .
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)
}
}
}
그 뒤에 data class 를 만들어줍니다 . NotificationData로 칭했습니다.
자신이 보낼 메세지나 데이터를 넣어주는 부분입니다.
data class NotificationData (
val title: String,
val message: String,
)
그리고 data class를 하나 더 만들어줍니다 . data를 담은 것을 누구에게 보낼것인가 하는 부분입니다 .
data 를 보시면 전에 만들었던 NotificationData 가 들어가는 것을 확인할 수 있습니다.
data class PushNotification (
val data: NotificationData,
val to: String
)
자 마지막으로 class FirebaseService 를 만들어줍니다.
private const val CHANNEL_ID = "my_channel"
class FirebaseService : FirebaseMessagingService() {
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_android_black_24dp)
.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)
}
}
이제 2탄의 마지막
manifest 로 가셔서 service를 추가하겠다고 선언을 해줍니다 .
<service
android:name=".FirebaseService"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
'안드로이드' 카테고리의 다른 글
안드로이드 스튜디오 네이버 파파고 api 사용해보기! (Java) (0) | 2021.11.17 |
---|---|
FCM 토큰 이용해서 상대방에게 메세지 날리기 (feat.Retrofit) 3편 (0) | 2021.11.11 |
FCM 토큰 이용해서 상대방에게 메세지 날리기 (feat.Retrofit) 1편 (0) | 2021.11.09 |
Sharedpreferences 사용해서 자동로그인 기능 추가하기! 2편 (Kotlin) (0) | 2021.10.19 |
Sharedpreferences 사용해서 자동로그인 기능 추가하기! 1편 (Kotlin) (0) | 2021.10.12 |