과정
- 토큰 요청 및 획득
- 서버에 토큰 저장
- 토큰을 이용해 메시지 전송 요청
- 메시지 전송
- 리스너를 통해 메시지 수신
FIrebase 페이지에 앱 등록 및 프로젝트 설정
- google-services.json을 앱 모듈 루트 디렉토리에 설치
// build.gradle(:Project)
buildscript{
repositories{}
dependencies{
classpath 'com.google.gms:google-service:4.3.5'
}
}
//build.greadle(:module)
dependencies {
implementation 'com.google.firebase:firebase-messaging:21.1.0'
}
// 가장 밑 한줄 추가
apply plugin: 'com.google.gms.google-services'
public class MyFirebaseMessagingService extends
FirebaseMessageing{
@Override
public void onNewToken(@NonNull String token){
super.onNewToken(token);
}
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage){
super.onMessageReceived(remoteMessage);
}
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.maejin.samplepush">
<uses-permission android:name="android.permission.INTERNET"/>
<application
...>
<activity android:name=".MainActivity">
...
</activity>
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
FirebaseMessaging.getInstance().getToken().addOnSuccessListener(new
OnSuccessListener<String>(){
@Override
public void onSuccess(String token){
}
});
메시지 수신처리
@Override
public void onMessageReceived(@NonNull RemoteMessage
remoteMessage){
super.onMessageReceived(remoteMessage);
NotificationManagerCompat notifivationManager =
NotificationManagerCompat.from(getApplicationContext());
NotificationCompat.Builder builder = null;
if(BUilde.VERSION.SDK_INT >= Build.VERSION_CODES.0){
if(notificationManager.getNotificationChannel(CHANNEL_ID) == null){
NotificationChannel channel = new
NotificationChannel(CHANNEL_ID, CHANNEL_NAME,
NotificatinoManager.IMPORTANCE_DEFAULT);
norificationManager.createNotificationChannel(channel);
}
builder = new
NotificationCompat.Builder(getApplicationContext(),
CHANNEL_ID);
}else {
builder = new
NotificationCompat.Builder(getApplicationContext());
}
String title =
remoteMessage.getNorification().getTitle();
String body = remoteMessage.getNorification().getBody();
builder.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_launcer_background);
Notification notification = builder.build();
notificationManager.norify(1, notification);
}