Android, Firebase 앱 등록 및 Firebase Push알림

이도현·2023년 8월 11일
0

Android 공부

목록 보기
8/30

과정

  • 토큰 요청 및 획득
  • 서버에 토큰 저장
  • 토큰을 이용해 메시지 전송 요청
  • 메시지 전송
  • 리스너를 통해 메시지 수신

FIrebase 페이지에 앱 등록 및 프로젝트 설정

  • google-services.json을 앱 모듈 루트 디렉토리에 설치
// build.gradle(:Project)
buildscript{
	repositories{}
	dependencies{
		classpath 'com.google.gms:google-service:4.3.5'
	}
}
//build.greadle(:module)

dependencies {
	implementation 'com.google.firebase:firebase-messaging:21.1.0'
}
// 가장 밑 한줄 추가
apply plugin: 'com.google.gms.google-services'
public class MyFirebaseMessagingService extends
FirebaseMessageing{
	@Override
	public void onNewToken(@NonNull String token){
		super.onNewToken(token);
		//token을 서버로 전송
	}

	@Override
	public void onMessageReceived(@NonNull RemoteMessage remoteMessage){
		super.onMessageReceived(remoteMessage);
		//수신한 메시지를 처리
	}
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.maejin.samplepush">
    
    <!--   INTERNET 퍼미션 추가!   -->
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        ...>
        <activity android:name=".MainActivity">
            ...
        </activity>

        <!--   서비스를 추가하고 인텐트 필터를 설정한다.   -->
        <service android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
    </application>

</manifest>
FirebaseMessaging.getInstance().getToken().addOnSuccessListener(new
OnSuccessListener<String>(){
	@Override
	public void onSuccess(String token){
		//등록된 토큰을 확인
	}
});

메시지 수신처리

@Override
public void onMessageReceived(@NonNull RemoteMessage
remoteMessage){
	super.onMessageReceived(remoteMessage);

	NotificationManagerCompat notifivationManager = 
NotificationManagerCompat.from(getApplicationContext());

	NotificationCompat.Builder builder = null;
	if(BUilde.VERSION.SDK_INT >= Build.VERSION_CODES.0){
		if(notificationManager.getNotificationChannel(CHANNEL_ID) == null){
		NotificationChannel channel = new
NotificationChannel(CHANNEL_ID, CHANNEL_NAME,
NotificatinoManager.IMPORTANCE_DEFAULT);

norificationManager.createNotificationChannel(channel);
	}
	builder = new
NotificationCompat.Builder(getApplicationContext(),
CHANNEL_ID);
	}else {
		builder = new
NotificationCompat.Builder(getApplicationContext());
	}

	String title =
remoteMessage.getNorification().getTitle();
	String body = remoteMessage.getNorification().getBody();

	builder.setContentTitle(title)
				 .setContentText(body)
				 .setSmallIcon(R.drawable.ic_launcer_background);
	
	Notification notification = builder.build();
	notificationManager.norify(1, notification);
}
profile
좋은 지식 나누어요

0개의 댓글