3

I have given my couple of days to solve this issue. My app is getting crash whose android version is 8.1. It is working perfectly fine in Android Version 8.0.

I followed the link mentioned below for the solution and tried many solutions given in this link but my application is not opening.

startForeground fail after upgrade to Android 8.1

I check the Android version in FirebaseMessageService class and create the channel for Oreo version but below given error is showing everytime

 android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:171)
        at android.app.ActivityThread.main(ActivityThread.java:6649)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)

Here below is my code. Please help me to rectify this problem

    public class MyFirebaseMessagingService extends FirebaseMessagingService
    {
        private NotificationManager notifManager;
        Context mContext;
        Random random = new Random();
        int m = random.nextInt(9999 - 1000) + 1000;

        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) 
        {
           sendNotification();
        }



   public void sendNotification()
   {
   Intent intent = new Intent(this, Home.class);
   intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
   PendingIntent pendingIntent = PendingIntent.getActivity(this, m /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

   String channelId = getString(R.string.default_notification_channel_id);
   Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
   NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
                   .setSmallIcon(R.drawable.app_icon)
                   .setContentTitle("Logipace")
                   .setStyle(new NotificationCompat.BigTextStyle()
                           .bigText(message))
                   .setContentText(message)
                   .setAutoCancel(true)
                   .setSound(defaultSoundUri)
                   .setContentIntent(pendingIntent);
   notificationBuilder.setDefaults(Notification.DEFAULT_SOUND);

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

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    {
        NotificationChannel channel = new NotificationChannel(channelId, "LOGIPACE", NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    notificationManager.notify(m /* ID of notification */, notificationBuilder.build());

    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
}
    }

Below is the code which I used in the onCreate() method of my Activity class.

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            // Create channel to show notifications.
            String channelId  = getString(R.string.default_notification_channel_id);
            String channelName = getString(R.string.default_notification_channel_name);
            NotificationManager notificationManager =
                    getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(new NotificationChannel(channelId,
                    channelName, NotificationManager.IMPORTANCE_LOW));
        }

Help me to resolve this issue.

Dnveeraj
  • 117
  • 3
  • 15
  • Possible duplicate of [startForeground fail after upgrade to Android 8.1](https://stackoverflow.com/questions/47531742/startforeground-fail-after-upgrade-to-android-8-1) – Khaled Lela Oct 18 '18 at 07:30
  • Well I solved my problem, I used startForegroundService() method somewhere in my Location Tracking class. else the above code is working perfectly fine. – Dnveeraj Oct 20 '18 at 07:28
  • Can you send the value of 'R.string.default_notification_channel_id'? – Thamarai T Apr 09 '19 at 10:02

1 Answers1

0

Put your logic inside onMessageReceived: Check Firebase quickstart sample.

public void onMessageReceived(RemoteMessage remoteMessage) {
    // Handle data payload of FCM messages.
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        Map<String, String> params = remoteMessage.getData();
        JSONObject object = new JSONObject(params);
        if (/* Check if data needs to be processed by long running job */ true) {
            // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
            scheduleJob();
        } else {
            // Handle message within 10 seconds
            final String msg = object.getString("msg");
            sendNotification(msg);
            handleNow();
        }

    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }
}

private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, Home.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    String channelId = getString(R.string.default_notification_channel_id);
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.ic_stat_ic_notification)
                    .setContentTitle(getString(R.string.fcm_message))
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

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

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }
    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
Khaled Lela
  • 7,831
  • 6
  • 45
  • 73
  • I created my own channel, while I am checking the version. The code is same as I see @Khaled Lela – Dnveeraj Oct 18 '18 at 07:20
  • I mentioned the same link above in my question, that I refer this link for the solution. – Dnveeraj Oct 18 '18 at 07:32
  • I will try to simulate same case to be able to help. – Khaled Lela Oct 18 '18 at 07:33
  • Why you put logic on `onCreate` method, You have to put on `onMessageReceived ` – Khaled Lela Oct 18 '18 at 07:56
  • because the link you provide me for solution, has done the same. Check the second solution of that link. The person is saying to put this logic on the onCreate() of Service. – Dnveeraj Oct 18 '18 at 08:01
  • `FirebaseMessagingService` will not need startForground system will handle that. – Khaled Lela Oct 18 '18 at 08:04
  • Android O and above create NotificationChannel, otherwise you builder, No need to use startForground() in this context. Please that and feedback – Khaled Lela Oct 18 '18 at 08:16
  • Ok I will remove the startForeground() and I also saw your edited answer above, I will apply it and let you know. – Dnveeraj Oct 18 '18 at 08:16
  • Please check google firebase [Quickstart sample](https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/java/MyFirebaseMessagingService.java) – Khaled Lela Oct 18 '18 at 08:28
  • I tried the Quickstart Sample given by firebase, but I am facing the same error. I am editing the my question code. Please look at that @Khaled Lela – Dnveeraj Oct 18 '18 at 10:09
  • Please consider `channel_id` Must be unique per package. – Khaled Lela Oct 18 '18 at 11:24
  • I tested same code and it's working with me, Please update your question with logcat crash, – Khaled Lela Oct 18 '18 at 14:29
  • Well I solved my problem, I used startForegroundService() method somewhere in my Location Tracking class. – Dnveeraj Oct 20 '18 at 07:27