Android
[Android] FCM 적용하기
sjwiq200
2020. 6. 3. 15:10
728x90
반응형
안녕하세요 오늘은 FCM에 대해서 정리를 하려고 합니다!
이전에 하려고 했는데 드디어 포스팅을 할 수 있게 되네요!
1. 우선 파이어베이스 콘솔에 들어가서 프로젝트를 만들어줍니다~!
https://console.firebase.google.com/
로그인 - Google 계정
하나의 계정으로 모든 Google 서비스를 Google 계정으로 로그인
accounts.google.com
프로젝트를 만들게 되면 Cloud Messaging에 들어가줍니다
안드로이드를 사용할 것이기 떄문에 안드로이드 아이콘을 이용하여 시작해줍니다.
그리고 나서 google-services.json 파일을 다운로드 하여줍니다!
2. 그리고 앱 모듈 루트 디렉토리에 넣어주세요~!
(프로젝트의 Hierarchy 구조를 Project로 바꾸신 후 app 밑에다가 넣어주세요~!)
3. 그리고 sdk 를 추가해주세요!
analytics는 추가하셔도 되고 안하셔도 됩니다!
4. 앱 수준의 build.gradle에 다음 항목을 추가해줍니다.
implementation 'com.google.firebase:firebase-messaging:20.0.0'
5. 앱 메니페스트 수정 (AndroidManiFest.xml)
application 태그 안에 다음을 작성해줍니다.
- 백그라운드에서 앱의 알림을 수신하는 것 외에 다른 방식으로 메시지를 처리하려는 경우에 필요합니다
<service
android:name=".java.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
## 선택사항
- 구성요소에 기본 알림 아이콘 및 색상을 설정하는 메타데이터 요소를 추가합니다.
- Android 8.0(API 수준 26) 이상부터는 알림 채널이 지원 및 권장됩니다.
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
See README(https://goo.gl/l4GJaQ) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_stat_ic_notification" />
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
notification message. See README(https://goo.gl/6BKBk7) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
이렇게 하면 우선 셋팅은 마무리가 됩니다.
현재 등록 토큰 얻기
FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Toast.makeText(mContext, "token :: "+ task.getResult().getToken(), Toast.LENGTH_LONG).show();
deviceToken = task.getResult().getToken();
}
});
메시지 받을 경우 처리하기
- 새 토큰이 생성될 때마다 onNewToken 콜백이 호출됩니다.
- 메시지를 받을경우 onMessageReceived 메소드를 사용하여 처리하면 됩니다!
public class FirebaseInstanceIDService extends FirebaseMessagingService {
private static final String TAG = "FirebaseMsgService";
public static final int NOTIFICATION_CHANNEL_ID = 90080;
private int mNotiID = 0;
@Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);
// 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.
}
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("sjwiq200 ==>" , "onMessageReceived");
}
}
메시지를 처리하는 방법은 다음에 포스팅을 하려고 합니다~!
감사합니다.
728x90
반응형