2

If I generate the Notification from Firebase notification icon is not coming.(App is in background). Icon is coming if App is in foreground.

I came to know that after lot of research. If App is in background it won't call OnmessageReceivedmethod(); So for that we have to override OnHandleIntent() method but I am unable to override it .Why because it is final..

Please give me some solution for this??

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
prakash421
  • 139
  • 1
  • 8
  • 1
    Have you tried this https://stackoverflow.com/a/37845174/3789481 ? – Tấn Nguyên Feb 26 '18 at 05:14
  • Please just check your code, may be you has written something that stop your service. **FCM automatically displays the message to end-user devices on behalf of the client app.Notification messages have a predefined set of user-visible keys.** – Mahesh Keshvala Feb 26 '18 at 05:24

3 Answers3

0
[![enter image description here][1]][1]           
 import android.app.ActivityManager;
            import android.app.Notification;
            import android.app.NotificationManager;
            import android.app.PendingIntent;
            import android.content.Context;
            import android.content.Intent;
            import android.content.SharedPreferences;
            import android.os.Build;
            import android.support.v4.app.NotificationCompat;
            import android.text.Html;
            import android.util.Log;

            import com.google.firebase.messaging.FirebaseMessagingService;
            import com.google.firebase.messaging.RemoteMessage;

            import org.json.JSONException;
            import org.json.JSONObject;

            import java.util.List;

            public class FirebaseMessagingReceiveService extends FirebaseMessagingService {
                private NotificationManager mNotificationManager;
                NotificationCompat.Builder builder;
                private String the_message = "";
                private String the_title = "ALERT_TITLE";
                public static final String TAG = "FCM Demo";

                private Context mContext;

                @Override
                public void onMessageReceived(RemoteMessage remoteMessage) {
                    if (remoteMessage == null)
                        return;


                    // Check if message contains a data payload.
                    if (remoteMessage.getData().size() > 0) {
                        Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

                        try {
                            JSONObject json = new JSONObject(remoteMessage.getData().toString());
                            handleDataMessage(json);
                        } catch (Exception e) {
                            Log.e(TAG, "Exception: " + e.getMessage());
                        }
                    }
                }


                private void handleDataMessage(JSONObject json) {
                    Log.e(TAG, "push json: " + json.toString());

                    try {
                        the_title = json.getString("DgTitle");
                        the_message = json.getString("DgMessage");

                        sendNotification(the_message, the_title);
                    } catch (JSONException e) {
                        Log.e(TAG, "Json Exception: " + e.getMessage());
                    } catch (Exception e) {
                        Log.e(TAG, "Exception: " + e.getMessage());
                    }
                }

                private void sendNotification(String msg, String theTitle) {
                    mContext = getApplicationContext();
                    mNotificationManager = (NotificationManager)
                            this.getSystemService(Context.NOTIFICATION_SERVICE);


                    ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                    List<ActivityManager.RunningTaskInfo> services = activityManager
                            .getRunningTasks(Integer.MAX_VALUE);
                    boolean isActivityFound = false;

                    if (services.get(0).topActivity.getPackageName().toString()
                            .equalsIgnoreCase(getPackageName().toString())) {
                        isActivityFound = true;
                    }
                    Intent openIntent = null;
                    if (isActivityFound) {
                        openIntent = new Intent();
                    } else {
                        openIntent = new Intent(this, MainActivity.class);
                        openIntent.putExtra("Title", the_title);
                        openIntent.putExtra("Message", the_message);
                        openIntent.setAction(Long.toString(System.currentTimeMillis()));
                    }
                    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                            openIntent, PendingIntent.FLAG_ONE_SHOT);


                    if (msg != null && (!msg.isEmpty())) {
                        NotificationCompat.Builder mBuilder =
                                new NotificationCompat.Builder(this)
                                        .setDefaults(Notification.DEFAULT_ALL)
                                        .setVibrate(new long[]{100, 250, 100, 250, 100, 250})
                                        .setAutoCancel(true)
                                        .setColor(getResources().getColor(R.color.activity_toolbar_color))
                                        .setContentTitle(theTitle)
                                        .setStyle(new NotificationCompat.BigTextStyle()
                                                .bigText(Html.fromHtml(msg)))
                                        .setPriority(Notification.PRIORITY_MAX)
                                        .setContentText(Html.fromHtml(msg));

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            mBuilder.setSmallIcon(R.drawable.notification_icon1);
                        } else {
                            mBuilder.setSmallIcon(R.drawable.notification_icon);
                        }

                        mBuilder.setContentIntent(contentIntent);


                        SharedPreferences prefs = mContext.getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
                        int notificationNumber = prefs.getInt("notificationNumber", 0);

                        // create unique id for each notification
                        mNotificationManager.notify(notificationNumber, mBuilder.build());

                        SharedPreferences.Editor editor = prefs.edit();
                        if (notificationNumber < 5000)
                            notificationNumber++;
                        else
                            notificationNumber = 0;

                        editor.putInt("notificationNumber", notificationNumber);
                        editor.commit();
                        Log.d("notificationNumber", "" + notificationNumber);

                    }
                }
            }


    this help to start FCM service in background when phone start.

        > 
        > Add receiver in Manifest.xml

        <uses-permission android:name="android.permission.WAKE_LOCK" />
        <receiver android:name=".OnBootBroadcastReceiver">
                    <intent-filter>
                        <action android:name="android.intent.action.BOOT_COMPLETED" />
                    </intent-filter>
        </receiver>

        > OnBootBroadcastReceiver.class

        import android.content.BroadcastReceiver;
        import android.content.Context;
        import android.content.Intent;

        public class OnBootBroadcastReceiver extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                Intent i = new Intent("com.examle.FirebaseMessagingReceiveService");
                i.setClass(context, FirebaseMessagingReceiveService.class);
                context.startService(i);
            }
        }

    > Add following dependency in app gradle.

     //Used for firebase services
        compile 'com.google.firebase:firebase-core:11.8.0'
        compile 'com.google.firebase:firebase-messaging:11.8.0'
    }


  [1]: https://i.stack.imgur.com/lcCZK.png
jessica
  • 1,700
  • 1
  • 11
  • 17
  • jaspreet Kaur did'nt worked for me.it still shows grey background with square instead of notification – prakash421 Feb 26 '18 at 05:47
  • please check this issue https://stackoverflow.com/questions/39157134/grey-square-as-notification-icon-using-firebase-notifications – jessica Feb 26 '18 at 06:33
  • please note notification_icon1 needed to be 144 X 144 PNG 32 bit color notification_icon needed to be 48 X 48 PNG 32 bit color – jessica Feb 26 '18 at 07:08
  • 144×144 is too big size. For notification_icon1 and notification_icon is 48×48 If I set same size of icons is it will work For sure.. Please confirm me that Your code is working for you in both forground and background. – prakash421 Feb 26 '18 at 07:13
  • yes, the code is working, the issue is with notification_icon1.. check it and let me know – jessica Feb 26 '18 at 07:22
  • Not working jaspreet..please share your icons and class files i will try..Thank you so much for your help and support – prakash421 Feb 26 '18 at 08:01
  • please check i have added notification icon – jessica Feb 26 '18 at 08:50
0

notification icon 1

please use this icon for notification icon 1

jessica
  • 1,700
  • 1
  • 11
  • 17
  • 1. resize image 144 X 144 PNG 2. then use the following link to create transparent background image https://www140.lunapic.com/editor/ – jessica Feb 26 '18 at 08:50
  • I tried with your Image it is not working ..It is not even going to OnmessageReceived() method if App is in background – prakash421 Feb 26 '18 at 09:22
  • have you add BroadcastReceiver given in my 1 answer – jessica Feb 26 '18 at 09:57
0

If you have difficulty in setting the icon size use android studio's image asset maker in android studio 3.0.1 which also allows to generate notification icon.

Also try to make your icon single color.

Also set the default icon for firebase notification:

<meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_notification_default" />
Umar Hussain
  • 3,461
  • 1
  • 16
  • 38