안드로이드 FCM 푸시 알림 사용하기
FCM (Firebase Cloud Messaging)은 이름답게 알림 메시지를 주고 받을 수 있게 해주는 서비스다.
대표적인 푸시 알림 서비스로는 iOS의 APNS, 안드로이드의 FCM이 있는데.
FCM은 APNS와 연동해서 iOS에서도 사용하거나, Unity, C++, 웹에서 사용이 가능하다.
우선 안드로이드 스튜디오에서 코드를 작성하기 전 파이어베이스 콘솔 (https://console.firebase.google.com/) 에서 프로젝트를 생성해야한다.
프로젝트를 생성했다면, 안드로이드 스튜디오 Tools 메뉴의 Firebase를 클릭하면,
위 사진과 같이 Firebase 설정 창이 나온다.
Firebase 설정 창에서 Cloud Messaging -> Set up Firebase Cloud Messaging을 클릭하면 위 사진과 같이 나온다.
여기서 Connect to Firebase를 클릭한다.
그러면 구글 계정에 로그인 해, Firebase 프로젝트와 연동이 가능해진다.
연동이 정상적으로 되면, Add FCM to your app을 클릭하면 자동으로 의존성 패키지들을 설치한다.
그 다음, AndroidManifest.xml 에 Firebase 관련 항목들을 추가해줘야 한다.
<service
android:name=".FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service
android:name=".FirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
이런식으로 FirebaseMessagingService와 FirebaseInstanceIDService를 만들어준다.
우선 FirebaseInstanceIDService는 토큰을 조회하고, 해당 토큰을 서버에 전송하는 역할을 하는 클래스다.
FirebaseInstanceIDSerivce 클래스를 추가해주자.
public class FirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "FirebaseIIDService";
@Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token : " + refreshedToken);
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
}
}
이런식으로 FirebaseInstanceIdService를 상속받아 만들어주면 된다.
그 다음, FirebaseMessagingService를 상속받아 FirebaseMessagingService를 만들어준다.
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From : " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
handleNow();
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Msg Notify Body : " + remoteMessage.getNotification().getBody());
}
}
public void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.icon)
.setContentTitle("한양알림이")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
그 다음, 이런식으로 메세지를 받는 메소드, 알림을 띄워주는 메소드를 작성해주면 된다.
이제 Firebase 콘솔에서 메세지를 보내면,
이렇게 알림이 뜨는 걸 확인할 수 있다.