I have two applications, when such an action occurs in one of the two applications, it sends a notification via FCM, to the other application, when the notification arrives, it only makes the notification noise if the application is open, when it is closed notification arrives silently
Here is the code for the app receiving notifications:
public class MyFirebaseMessaging extends FirebaseMessagingService {
@Override
public void onMessageReceived(final RemoteMessage remoteMessage) {
if (remoteMessage.getNotification().getTitle().equals("Entrega")) {
showNotificacaoTeste(remoteMessage.getNotification().getBody());
}
}
private void showNotificacaoTeste(String body) {
PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(), 1 ,new Intent(),PendingIntent.FLAG_ONE_SHOT );
NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());
builder.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Entrega")
.setContentText(body)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setContentIntent(contentIntent);
NotificationManager manager = (NotificationManager)getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1,builder.build());
}
}
Code that sends the notification to the other application
private void cancelarEntrega(String clienteId) {
Token token = new Token(clienteId);
Notification notification = new Notification("Entrega", "O entregador não aceitou a entrega");
Sender sender = new Sender(token.getToken(), notification);
mFCMService.sendMessage(sender)
.enqueue(new Callback<FCMResponse>() {
@Override
public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) {
if (response.body().success == 1) {
finish();
}
}
@Override
public void onFailure(Call<FCMResponse> call, Throwable t) {
}
});
}
Notification Model
public class Notification {
public String title;
public String body;
public Notification(String title, String body) {
this.title = title;
this.body = body;
}
}
Sender Model:
public class Sender {
public String to;
public Notification notification;
public Sender(String to, Notification notification) {
this.to = to;
this.notification = notification;
}
}