무료 푸시 알림 서비스다.
일단 무료인게 엄청 크다.
이를 통해 사용자가 백엔드 서버에서 모바일 앱으로 푸시 알림을 보낼 수 있고, 이를 이용하여 SNS 앱이 열리거나 카메라가 켜질 때 백그라운드에서 알림을 보내는 기능을 구현할 수 있다.
google-services.json
파일을 다운로드하고, Android 프로젝트의 app
폴더에 추가한다.build.gradle
파일에서 Firebase SDK와 관련된 의존성을 추가한다.
build.gradle
:
classpath 'com.google.gms:google-services:4.3.14' // 최신 버전 확인
build.gradle
:
implementation 'com.google.firebase:firebase-messaging:23.0.0' // 최신 버전 확인
apply plugin: 'com.google.gms.google-services'
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(task -> {
if (!task.isSuccessful()) {
Log.w(TAG, "Fetching FCM registration token failed", task.getException());
return;
}
// Get new FCM registration token
String token = task.getResult();
Log.d(TAG, "FCM Token: " + token);
});
FirebaseMessagingService
클래스를 확장하여 메시지를 처리한다.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// 메시지 처리
if (remoteMessage.getNotification() != null) {
sendNotification(remoteMessage.getNotification().getBody());
}
}
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);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, "channel_id")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("New Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
firebase-admin
패키지를 설치하고, Firebase 프로젝트의 서비스 계정 키를 이용하여 메시지를 보낸다.
```javascript
const admin = require(‘firebase-admin’);
admin.initializeApp({
credential: admin.credential.cert(require(‘./path/to/serviceAccountKey.json’))
});const message = { notification: { title: ‘App opened’, body: ‘Your SNS app has been opened!’ }, token: ‘user-device-fcm-token’ };
admin.messaging().send(message) .then(response => { console.log(‘Message sent successfully:’, response); }) .catch(error => { console.error(‘Error sending message:’, error); }); ```
이 방법을 사용하여 앱에서 SNS 앱이 열리거나 카메라가 켜질 때 알림을 보내는 기능을 구현할 수 있다. FCM을 통해 백그라운드 작업을 트리거하고, 프론트엔드의 상태 플래그를 업데이트하는 추가 로직도 작성할 수 있다.
serviceAccountKey.json
와 google-services.json
파일 다운로드 방법serviceAccountKey.json
다운로드이 파일은 Firebase Admin SDK에서 사용할 서비스 계정 키 파일로, 백엔드에서 Firebase 기능을 사용할 때 필요하다.
serviceAccountKey.json
파일이 자동으로 다운로드된다.google-services.json
다운로드이 파일은 Android 애플리케이션에서 Firebase 기능을 연동할 때 필요하다.
google-services.json
파일을 다운로드할 수 있는 버튼이 생성된다. 이를 클릭하여 파일을 다운로드한다.이 두 파일은 각각 서버와 클라이언트에서 Firebase를 사용하기 위해 중요한 파일이니, 보안에 신경 써서 관리해야 한다.