안드로이드 FCM(Firebase Cloud Messaging) 사용하기
최근 구글에서 GCM지원을 완전 중지하면서 2019년 4월 11일까지 모든 GCM사용 클라이언트를 FCM으로 업그레이드 하라고 발표했습니다. 이 이후 GCM서비스는 제거됩니다. FCM을 사용하는 법은 그리 어렵지 않으니 잘 따라오시기 바랍니다.
Firebase Console에 프로젝트 추가하기
FCM을 클라이언트에 추가하기
그 다음 프로젝트에 들어갑니다.
왼쪽 메뉴바에서 스크롤을 아래로 내려 Cloud Messaging을 클릭한 뒤, 안드로이드 아이콘을 눌러주시기 바랍니다.
그러면 이제 FCM사용을 위해 앱 등록을 진행하게 됩니다.
패키지 이름에는 FCM을 사용할 앱의 패키지명을 등록해 주시면 됩니다. AndroidManifest.xml 파일을 열어 보시면, 아래와 같은 소스가 보이실 겁니다.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="space.codejun.firebasemsg">
저 manifest 태그 속 package라고 적혀있는 부분이 자신의 패키지명입니다. 저는 space.codejun.firebasemsg 가 되겠습니다. 저 부분을 맨 윗칸에 작성해 주세요.
저희는 일단 FCM만 사용하는 것으로 진행하기 때문에 이외 선택사항은 생략하고, 그 다음 앱 등록을 진행합니다.
이제 구성 파일을 다운로드 합니다. 저 파일을 다운 받은 뒤, app디렉토리 안에 넣어주시기 바랍니다.
위 사진과 같이 보기 방식을 Project로 변경하고, app폴더에 집어 넣으시면 훨씬 편하게 작업하실 수 있습니다.
이제 추가가 완료 되었습니다.
그 다음 Gradle을 추가해 주어야 하는데요, project수준 build.gradle에 아래 소스를 추가합니다.
buildscript { dependencies { // Add this line classpath 'com.google.gms:google-services:3.2.0' } }
app단 build.gradle에는 아래 소스를 넣어주세요.
dependencies { // Add this line compile 'com.google.firebase:firebase-messaging:11.8.0' } ... // Add to the bottom of the file apply plugin: 'com.google.gms.google-services'
그 다음 Sync를 진행해 주시기 바랍니다.
메세지를 받기 위한 작업
첫번째로, FirebaseInstanceIDService 와 두번째로, FireBaseMessagingService 입니다.
아래 소스코드를 추가해 주시기 바랍니다.
FirebaseInstanceIDService.class
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class FirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
// [START refresh_token]
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(refreshedToken);
}
// [END refresh_token]
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* @param token The new token.
*/
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
}
}
FireBaseMessagingService.class
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class FireBaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be: https://goo.gl/39bRNJ
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
} else {
// Handle message within 10 seconds
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
// [END receive_message]
/**
* Handle time allotted to BroadcastReceivers.
*/
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
/**
* Create and show a simple notification containing the received FCM message.
*
* @param messageBody FCM message body received.
*/
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 /* Request code */, 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.mipmap.ic_launcher)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create channel to show notifications.
String channelName = getString(R.string.default_notification_channel_name);
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
그 다음, Manifest에 다시 돌아와서 아래 소스들을 추가해 줍니다.
</activity> 태그 아래다 넣어주세요.
<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>
알림채널 설정
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create channel to show notifications.
String channelName = getString(R.string.default_notification_channel_name);
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
위와같은 소스코드를 보실 수 있는데, 이 부분의 알림채널에 관한 소스입니다.
오레오 이상 버전일때 알림채널을 생성하고 관리할 수 있는 부분이죠. IMPORTANCE_HIGH 부분을 조절하여, 알림의 중요도를 설정 가능합니다. 소리를 낼건지, 진동을 울릴건지 등 결정하는 부분입니다. 등급에 따라 다르니 아래 사진을 참고 하시고, 그래도 모르시겠다면, 도움이 될만한 링크를 걸어두겠습니다. 참고하시기 바랍니다.
알림 보내기
위와같이 앱 타겟팅을 처음 등록해놓은 패키지명의 앱으로 선택하고, 메세지를 작성하고 보내봅니다.
Logcat과 기기에서 정상적으로 뜨는 것을 확인하실 수 있습니다.
마무리
이로써 모든 설정 및 사용 준비가 끝났습니다. GCM보다 쉽고 간편한 FCM은 여러 방면으로도 커스터마이징이 가능한 좋은 놈입니다.
하시다가 잘 모르시는 부분이 있으시다면, 언제든지 댓글 남겨주시면 제가 갖고 있는 지식에 한에서 최대한 도움 드릴 수 있도록 노력하겠습니다. 공지사항에 제 개인적인 연락처도 있으니 편하신 방법으로 문의 주세요!
감사합니다!
'Android' 카테고리의 다른 글
Google I/O Extended Seoul 참가 후기 (0) | 2018.06.12 |
---|---|
Android Studio에서 Firebase Assistant 사용하기 (With. Dynamic Links) (2) | 2018.06.03 |
ML Kit 을 사용하여 간편하게 머신러닝 사용하기 (1) | 2018.05.25 |
Gradle용 Android 플러그인 업데이트 (0) | 2018.05.05 |
아두이노, 안드로이드 블루투스 통신하기 (180) | 2018.04.23 |
댓글
이 글 공유하기
다른 글
-
Android Studio에서 Firebase Assistant 사용하기 (With. Dynamic Links)
Android Studio에서 Firebase Assistant 사용하기 (With. Dynamic Links)
2018.06.03 -
ML Kit 을 사용하여 간편하게 머신러닝 사용하기
ML Kit 을 사용하여 간편하게 머신러닝 사용하기
2018.05.25 -
Gradle용 Android 플러그인 업데이트
Gradle용 Android 플러그인 업데이트
2018.05.05 -
아두이노, 안드로이드 블루투스 통신하기
아두이노, 안드로이드 블루투스 통신하기
2018.04.23