Powiadomienie fcm na Androida jest odbierane na Androidzie z interfejsami API niższymi niż 26, jednak interfejsy API 26 (Oreo 8.0) tego nie robią i powodują zawieszenie aplikacji

==================== MyFirebaseMessagingService =============================== ==

    public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String channel_id = "the_id";


 @Override
 public void onNewToken(String s) {
super.onNewToken(s);
Log.e("NEW_TOKEN",s);
updateTokenToFirebase(s);

  }


 private void updateTokenToFirebase(String token) {
IDrinkShopAPI mService = Common.getAPI();

mService.updateToken("SERVER_01",token,"0")
        .enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.d("DEBUG_TOKEN",response.body());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.d("DEBUG_TOKEN",t.getMessage());
            }
        });


    }



     @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);

if(remoteMessage.getData() != null){

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        sendNotification26(remoteMessage);
    else
        sendNotification(remoteMessage);

  }

}

 private void sendNotification26(RemoteMessage remoteMessage) {
Map<String,String> data = remoteMessage.getData();

  String title = data.get("title");
  String message = data.get("message");



NotificationHelper helper ;
Notification.Builder builder;
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

helper = new NotificationHelper(this);

builder = helper.getDrinkShopNotification(title,message,defaultSoundUri);

helper.getManager().notify(new Random().nextInt(),builder.build());


 }


 private void sendNotification(RemoteMessage remoteMessage) {

Map<String,String> data = remoteMessage.getData();

 String title = data.get("title");
 String message = data.get("message");



Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle(title)
        .setContentText(message)
        .setAutoCancel(true)
        .setColor(ContextCompat.getColor(this, R.color.colorAccent))
        .setSound(defaultSoundUri);

NotificationManager mn =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

mn.notify(new Random().nextInt(),builder.build());

    }
  }

========================= NotificationHelper ======================== =========

// ta klasa jest używana do implementacji powiadomień dla API 26+

  public class NotificationHelper extends ContextWrapper {

  private static final String CHANNEL_ID = "the_id";
  private static final String CHANNEL_NAME = "Drink_Shop";

  private NotificationManager notificationManager;

 public NotificationHelper(Context base) {
  super(base);

   if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
     createChannel();
  }

  @TargetApi(Build.VERSION_CODES.O)
  private void createChannel() {

  NotificationChannel nc = new NotificationChannel(CHANNEL_ID,CHANNEL_NAME,
        NotificationManager.IMPORTANCE_DEFAULT);

   nc.enableLights(false);
   nc.enableVibration(true);
   nc.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

   getManager().createNotificationChannel(nc);

 }

 public NotificationManager getManager() {

 if(notificationManager == null)

    notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

return notificationManager;

 }

  @TargetApi(Build.VERSION_CODES.O)
  public Notification.Builder getDrinkShopNotification(String title,
                                                 String message,
                                                 Uri soundUri)
  {

return new Notification.Builder(getApplicationContext(),CHANNEL_ID)
        .setContentTitle(title)
        .setContentText(message)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setSound(soundUri)
        .setChannelId(CHANNEL_ID)
        .setColor(ContextCompat.getColor(this, R.color.colorAccent))
        .setAutoCancel(true);

  }


}

============================= Manifest ==================== ===================

   <service
    android:name=".Services.MyFirebaseMessagingService"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

============================ Build.gradle =================== =================

   implementation 'com.google.firebase:firebase-messaging:20.0.0'
   implementation 'com.google.firebase:firebase-core:17.2.1'
   implementation 'com.google.android.gms:play-services-auth:17.0.0'

=========================== IFCMService ====================== =================

    public interface IFCMService {

     @Headers({
    "Content-Type:application/json",
    "Authorization:mytoken"
   })
   @POST("fcm/send")
   Call<MyResponse> sendNotification(@Body DataMessage body);

}

========================== sendNotificationToServer ======================= ========

// ta metoda służy do wysyłania powiadomienia do aplikacji serwera

    private void sendNotificationToServer(OrderResult orderResult) {

   mService.getToken("SERVER_01", "1")
        .enqueue(new Callback<Token>() {
            @Override
            public void onResponse(Call<Token> call, Response<Token> response) {

                Map<String,String> contentSend = new HashMap<>();
                contentSend.put("title","NEW ORDER");
                contentSend.put("message","You have got new order" + orderResult.getOrderId());

                DataMessage dataMessage = new DataMessage();
                if(response.body().getToken() != null)
                    dataMessage.setTo(response.body().getToken());

                    dataMessage.setData(contentSend);

                    IFCMService ifcmService = Common.getFCMService();
                     ifcmService.sendNotification(dataMessage)
                        .enqueue(new Callback<MyResponse>() {
                            @Override
                            public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {

                                if(response.code() == 200){

                                    if(response.body().success == 1){

                                 Toast.makeText(CartActivity.this,
                                 getResources().getString(R.string.order_submitted), Toast.LENGTH_SHORT)
                                    .show();
                                        //Clear Carts From Room Database
                                        Common.cartRepository.emptyCart();
                                        //finish();
                                    }
                                    else {

                                        Toast.makeText(CartActivity.this, "Send Notification Failed", Toast.LENGTH_SHORT).show();
                                    }
                                }

                            }

                            @Override
                            public void onFailure(Call<MyResponse> call, Throwable t) {

                                Toast.makeText(CartActivity.this, ""+t.getMessage(), Toast.LENGTH_SHORT).show();

                            }
                        });

            }

            @Override
            public void onFailure(Call<Token> call, Throwable t) {

                Toast.makeText(CartActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });



   }
0
Eskandar Rushdi 20 listopad 2019, 18:40
1
Czy możesz dodać więcej informacji na temat otrzymywanego błędu
 – 
Pavan Varma
20 listopad 2019, 18:49
1
Zapomniałeś opublikować ślad stosu z awarii.
 – 
Michael
20 listopad 2019, 18:50
Udostępnij dziennik błędów.
 – 
Ashvin solanki
20 listopad 2019, 19:04
Właśnie zauważyłem, że aplikacja ulega awarii tylko na API 26 (Oreo 8.0). a stacktrace nie pokazuje żadnego komunikatu o błędzie, ale aplikacja ulega awarii.
 – 
Eskandar Rushdi
20 listopad 2019, 19:04
App show komunikat „UI systemu zatrzymał się”, jednak w Logcat nic nie widać!
 – 
Eskandar Rushdi
20 listopad 2019, 19:19

1 odpowiedź

Myślę, że niepotrzebnie komplikujesz kod.

Wypróbuj poniższy kod

private void createNotification(String title, String message) {

    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // only create notification channel if SDK >= 26
    if (android.os.Build.VERSION.SDK_INT >= 26) {
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);

        channel.enableLights(false);
        channel.enableVibration(true);
        channel.setDescription(CHANNEL_DESC);

        manager.createNotificationChannel(channel);
    }

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(android.R.drawable.stat_notify_more)
            .setContentTitle(title)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setSound(defaultSoundUri)
            .setColor(ContextCompat.getColor(this, R.color.colorAccent))
            .setContentText(message);


    manager.notify(new Random().nextInt(), builder.build());

}
0
Pavan Varma 20 listopad 2019, 19:29
Rozwiązałem to, zmieniając zasoby ikon powiadomień z mipmap na drawable
 – 
Eskandar Rushdi
20 listopad 2019, 19:33
W każdym razie spróbuj raz tego kodu. Twój kod jest zbyt skomplikowany, aby wyświetlać powiadomienia
 – 
Pavan Varma
20 listopad 2019, 19:35