4

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;
}

}
2
  • Você está mandando a mensagem do tipo data ou do tipo notification? Coloca também o código onde você envia a notificação.
    – KaduAmaral
    2/03/2018 às 21:12
  • Atualizei a pergunta @KaduAmaral
    – Paiva
    2/03/2018 às 21:21

2 Respostas 2

2

Não tenho certeza, mas isso pode estar acontecendo por causa do tipo da mensagem, você está mandando uma notificação do tipo "Notification", isso faz com que ela seja entregue direto para a "bandeja" de push do Android e não passa pela sua função onMessageReceived.

| Estado do app  | Notificação        | Dados             | Ambos                           |
| -------------- | ------------------ | ----------------- | ------------------------------- |
| Primeiro plano | onMessageReceived  | onMessageReceived | onMessageReceived               |
| Segundo plano  | Bandeja do sistema | onMessageReceived | Notificação: bandeja do sistema |

Envie com o tipo data, na sua classe Sender:

public Sender(String to, Notification notification) {
    this.to = to;
    this.data = notification; // <<-- Coloque como "data"
}

E pegue os dados com getData() (Não sou um programador Android, então não vou poder te ajudar muito nessa parte... rsrs)

// Coloque um break-point neste if e verifique se está entrando aqui com o APP fechado
if (remoteMessage.getData().get('title').equals("Entrega")) {
    showNotificacaoTeste(remoteMessage.getData().get('body'));
}

Documentação: onMessageReceived

5
  • testei com o data , mas nao deu certo nao =/
    – Paiva
    4/03/2018 às 0:07
  • Com o data a mensagem está passando pelo onMessageReceived com o app fechado?
    – KaduAmaral
    4/03/2018 às 0:33
  • Aparentemente não
    – Paiva
    4/03/2018 às 0:37
  • Amanhã vou tentar com mais calma
    – Paiva
    4/03/2018 às 0:37
  • Atualizei o código da resposta, quando conseguir testar me avise.
    – KaduAmaral
    5/03/2018 às 14:43
0

Na criação da notificação vc deve chamar o alarm

private void showNotificacaoTeste(String body) {
    //Uri do som do alarm
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);//Pega o alarm padrão do sistema, pode ser personalizado aqui

    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)
            .setSound(alarmSound);//Som é adicionado a notificação aqui

    NotificationManager manager = (NotificationManager)getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(1,builder.build());
}

O que mudou foi só builder.setSound(alarmSound); onde som é adicionado a notificação aqui

Fonte https://stackoverflow.com/a/15855464/4395789

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .