Possuo dois aplicativos, quando acontece tal ação em um dos dois aplicativos, ele envia uma notificação via FCM, para o outro aplicativo, quando chega a notificação , só faz o barulho de notificação se o aplicativo estiver aberto , quando ele está fechado a notificação chega silenciosamente
Segue o código do aplicativo receptor das notificações:
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());
}
}
Código que envia a notificação para o outro aplicativo
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) {
}
});
}
Model da notificação
public class Notification {
public String title;
public String body;
public Notification(String title, String body) {
this.title = title;
this.body = body;
}
}
Model do Sender:
public class Sender {
public String to;
public Notification notification;
public Sender(String to, Notification notification) {
this.to = to;
this.notification = notification;
}
}