FireBase 프로젝트 생성
- 해당 사이트에 접속합니다.
https://console.firebase.google.com/
로그인 - Google 계정
하나의 계정으로 모든 Google 서비스를 Google 계정으로 로그인
accounts.google.com
프로젝트 추가하기 클릭합니다.
프로젝트 이름 설정후 계속합니다.
필자는 애널리틱스 사용 안함으로 설정하였습니다.
안드로이드 모양을 클릭합니다.
Android 패키지 이름에는 manifest.xml 파일에 package명을 입력합니다.
앱등록 클릭
google-services.json 파일 다운후 프로젝트에 넣기
해당 google-services.json 파일을 받아서 app 폴더안에 넣습니다.
build.gradle 라이브러리 추가
프로젝트 기준 - build.gradle 파일을 열어서 해당 라인을 추가합니다.
classpath 'com.google.gms:google-services:4.3.10'
app 폴더안에 build.gradle 파일을 열어서 해당 라인을 추가합니다.
id 'com.google.gms.google-services'
implementation platform('com.google.firebase:firebase-bom:28.4.2')
implementation 'com.google.firebase:firebase-messaging:21.1.0'
첫번째라인에 있는거는 plugins에 추가합니다.
두번째, 세번째 라인에 있는거는 dependencies에 추가합니다.
소스수정
Mainfest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.chats">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="@style/Theme.AppCompat.NoActionBar">
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyFireBaseMessagingService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
아래소스를 MainActivity.java 클래스 oncreate문 안에 넣습니다.
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
if(!task.isSuccessful()){
Log.w("FCM Log", "getInstanceId faild", task.getException());
return;
}
// Get new FCM registration token
String token = task.getResult();
Log.d("FCM Log", "FCM 토근 : " + token);
Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
}
});
MyFireBaseMessagingService.java 생성
package com.example.chats;
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.util.Log;
import androidx.core.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFireBaseMessagingService extends FirebaseMessagingService {
@Override
public void onNewToken(String token) {
Log.d("FCM Log", "Refreshed token: " + token);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if(remoteMessage.getNotification() != null){
Log.d("FCM Log", "알림 메시지 : " + remoteMessage.getNotification().getBody());
String messageBody = remoteMessage.getNotification().getBody();
String messageTitle = remoteMessage.getNotification().getTitle();
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 = "Channel ID";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelName = "Channel Name";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}
}
}
FireBase 발송 테스트
firebase 사이트로 다시 돌아가서 Send your first message 클릭
타겟 아까 생성한 프로젝트로 설정후 검토클릭을 합니다.
테스트 결과
알림이 정상적으로 온것을 확인할수 있습니다.
'native > 안드로이드' 카테고리의 다른 글
[Android] 웹뷰 alert 네이티브 팝업으로 띄우기 (0) | 2021.10.26 |
---|---|
[Android] 안드로이드 앱아이콘 만들기 (0) | 2021.10.19 |
[안드로이드] 상단 타이틀바 없애기 (0) | 2021.10.06 |
[안드로이드] 웹뷰 카메라 호출 (0) | 2021.10.06 |
[안드로이드] 웹뷰 설정 (0) | 2021.10.06 |