Вам нужен класс службы обмена сообщениями Firebase.
создайте класс с именем MyFirebaseMessagingService
, который получит уведомление и расшифрует его.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
private static final String CHANNEL_ID = "MyFirebaseMessagingService";
String title;
String message;
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO: Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated.
title = "You have a new notification";
message = remoteMessage.getNotification().getBody();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("You have a new notification")
.setContentText(remoteMessage.getNotification().getBody());
int notificationId = (int) System.currentTimeMillis();
// Issue the notification.
NotificationManager notification = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
assert notification != null;
notification.notify(notificationId, mBuilder.build());
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, mBuilder.build());
createNotificationChannel();
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
}
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = title;
String description = message;
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
assert notificationManager != null;
notificationManager.createNotificationChannel(channel);
}
}
}
Добавьте метаданные внутри вашего Manifest.xml
, как следующие
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@mipmap/ic_launcher" />
Также добавьте следующую службу сообщений в ваш xml
<service android:name=".services.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>