Friebase 사용해서 push message 보내기
2021. 12. 2. 17:15ㆍAndroid Development
AndroidManifest.xml 에 푸시 알림시 사용할 채널, 컬러, 아이콘을 메타 정보로 등록.
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@mipmap/ic_launcher" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" /> <!-- fcm default notification channel id -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="1" />
cloudMessaging 패키지 생성
package com.example.fcmtest.cloudmessaging;
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.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import com.example.fcmtest.MainActivity;
import com.example.fcmtest.R;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
// 푸시 메세지를 수신했을때 동작.
if (remoteMessage.getData().size() > 0) {
Log.d("jaeho", "Message data payload: " + remoteMessage.getData());
if (false) {
// For long-running tasks (10 seconds or more) use WorkManager.
// Log.d("jaeho", "scheduleJob in");
scheduleJob();
} else {
// Handle message within 10 seconds
handleNow(remoteMessage);
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d("jaeho", "Message Notification Body: "
+ remoteMessage.getNotification().getBody());
}
}
}
private void scheduleJob() {
Log.d("jaeho", "scheduleJob in");
}
private void handleNow(RemoteMessage remoteMessage) {
Log.d("jaeho", "handleNow in");
// 푸시 메세지를 수신 했다면 알림창 띄우기.
sendNotification(remoteMessage.getData().get("message"));
}
private void sendNotification(String message) {
Log.d("jaeho", "sendNotification");
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// 수신된 어플을 활성화.
PendingIntent pendingIntent = PendingIntent.getActivity(this
, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
// PendingIntent = 예약 인텐트, 특정 주기가 됐을때 동작
String channelId = "1000";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//휴대폰 알림음 객체 생성
//알림 처리
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
//알림 관리자
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//안드로이드 버전별 예외 처리
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}
@Override
public void onNewToken(@NonNull String s) {
// 푸시 메세지 전송용 토큰 생성.
Log.d("jaeho", "onNewToken token = " + s);
sendRegistrationToServer(s);
}
private void sendRegistrationToServer(String s) {
Log.d("jaeho", "onNewToken token = " + s);
}
}
MyFirebaseMessagingService.java 생성
package com.example.fcmtest.cloudmessaging;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.example.fcmtest.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.installations.FirebaseInstallations;
public class CloudMessagingActivity extends AppCompatActivity
implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cloud_messaging);
Button tokenbtn = findViewById(R.id.tokenbtn);
tokenbtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
//파이어베이스가 초기화 된 후 그 객체를 통해서 아이디 가져오기
FirebaseInstallations.getInstance().getId()
.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
if (task.isSuccessful()) {
Log.d("jaeho", "Installation ID: "
+ task.getResult()+":1202");
} else {
Log.e("jaeho", "Unable to get Installation ID");
}
}
});
}
}
CloudMessagingActivity.java 생성
파이어베이스 콘솔에서 클라우드메세징탭
결과 화면
'Android Development' 카테고리의 다른 글
Firebase_RealtimeDatabase 사용 해보기. (0) | 2021.12.01 |
---|---|
Firebase로 로그인 처리하기 (0) | 2021.12.01 |
Google Firebase 환경설정. (0) | 2021.11.29 |
Android semiProject (0) | 2021.11.24 |
Android Studio 13일차 (0) | 2021.11.17 |