SMALL
1. Firebase에 프로젝트 생성
1.1. 안드로이드 스튜디오에 Firebase 추가
- 메뉴의 Tool -> Firebase -> CloudMessaging -> Set up Firebase Cloud Messaging
connect to firebase 클릭하면 웹에서 진행된다.
- 안드로이드 스튜디오에서 위에서 만든 프로젝트와 연결
- Add FCM 클릭
코드
더보기
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "ddwu.mobile.final_project.mypushtest"
minSdkVersion 15
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.firebase:firebase-messaging:17.3.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
//spring-boot-starter-jdbc
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc', version: '2.1.0.RELEASE'
}
관련 항목이 추가됨 확인.
2. FCM에서 백그라운드 알림을 받기 위한 코드 추가
2.1. 소스코드
2.1.1. MyFirebaseInstanceIDService
-FirebaseInstanceIdService와 onTokenRefresh() 메소드들이 구글 지원을 더이상 하지 않아 대체 메소드를 사용하였다.
코드
더보기
package ddwu.mobile.final_project.mypushtest;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import static android.content.ContentValues.TAG;
public class MyFirebaseInstanceService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String refreshedToken) {
//push로 보내는 코드
}
// 토큰이 새로 만들어질때나 refresh 될때
/** extends FirebaseMessagingService
@Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("NEW_TOKEN", refreshedToken);
// DB서버로 새토큰을 업데이트시킬수 있는 부분
}
// 메세지를 새롭게 받을때
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
// 새메세지를 알림기능을 적용하는 부분
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
String messageBody = remoteMessage.getNotification().getBody();
String messageTitle = remoteMessage.getNotification().getTitle();
}
}
**/
}
2.1.2. messagingService
더보기
package ddwu.mobile.final_project.mypushtest;
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 androidx.core.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
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);
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);
//사용자가 컴파일하는 SDK 버전을 정의하는 데 사용하는 compileSdkVersion보다 낮은 API 수준의 장치가 사용자에게있는 경우
// 알림을 표시하기 위해 채널을 생성하는 코드를 실행하지 않도록 요청하는 코드.
//오류가 발생하는데 해결방법을 찾지못해 주석처리함
// if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.0) {
//
// }
notificationManager.notify(0, notificationBuilder.build());
}
}
2.1.3. manifest 추가
더보기
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ddwu.mobile.final_project.mypushtest">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyFirebaseMessagingService">
</service>
<!-- <service-->
<!-- android:name=".MyFirebaseMsgService"-->
<!-- android:stopWithTask="false">-->
<!-- <intent-filter>-->
<!-- <action android:name="com.google.firebase.MESSAGING_EVENT" />-->
<!-- </intent-filter>-->
<!-- </service>-->
</application>
<meta-data
android:name="com.example.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
</manifest>
2.1.4. string.xml에 channel 로 사용할 값 넣기
<string name="default_notification_channel_id">test</string>
2.2
firebase 홈페이지에서 알림 생성 후 검토 버튼으로 알림전송해보기
상단바에 표시된 것을 확인할 수 있다.
3.1 Spring boot 환경 구성
3.1.1 Gradle
---
참고페이지
더보기
전체 가이드 : https://galid1.tistory.com/418?category=747889
FirebaseInstanceIdService의 구글 지원 중단 관련 참고 : https://wonpaper.tistory.com/192
SMALL
'기록 > Mobile' 카테고리의 다른 글
[Android] The ADB binary found at C: 오류 (0) | 2020.11.19 |
---|---|
[Android] android module not specified error (0) | 2020.11.19 |
[Android] Github 연동 및 사용 (0) | 2020.11.10 |
Android에서 Amazon Dynamo DB 사용하기 (0) | 2020.10.27 |
FCM오픈소스 가이드 따라하기 (0) | 2020.05.07 |