13

I won't show a received push notification from appearing top notifications menu my notification if it has for example key update. For now if I get notification with this key, all notifications are in the notification bar. I want to not present this notifications for user.

I'm using WakefulBroadcastReceiver for handle notifications like below:

public class PusherReceiver extends WakefulBroadcastReceiver {
    private boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null) 
            return false;

        final String packageName = context.getPackageName();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
                return true;
            }
        }

        return false;
    }

    public void onReceive(final Context context, Intent intent) {
        Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
        if (!isAppOnForeground((context))) {
            String pushNotificationBody = intent.getStringExtra("alert");

            try {
                JSONObject notificationData = new JSONObject(pushNotificationBody);

                // This is the Intent to deliver to our service.
                Intent service = new Intent(context, BackgroundService.class);
                // Put here your data from the json as extra in in the intent
                service.putExtra("notification", pushNotificationBody);

                Log.i("PUSH_NOTIFICATION_JSON", "RECEIVED JSON " + notificationData);

                // Start the service, keeping the device awake while it is launching.
                if (!notificationData.has("update")) {
                    startWakefulService(context, service);
                } else {
                    // Do nothing
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

UPDATE:

I changed project a little and with Onesignal and his NotificationExtenderService, I did something like below:

public class NotificationNotDisplayingExtender extends NotificationExtenderService {
    @Override
    protected boolean onNotificationProcessing(OSNotificationReceivedResult receivedResult) {
        String notification = receivedResult.toString();
        String notificationBody = receivedResult.payload.body;
        JSONObject notificationBodyJSON = null;
        try {
            notificationBodyJSON = new JSONObject(notificationBody);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JSONObject pushNotificationData = notificationBodyJSON;
        boolean hidden = false;

        if (pushNotificationData.has("update")) {
            Log.i("NOTIFICATION MANAGER", "PREVENT DISPLAY NOTIFICATION");

            hidden = true;
        }


        // Return true to stop the notification from displaying.
        return hidden;
    }
}

And it prevent displaying notifications with update key, but now I don't receive it in my PusherReceiver to start my service. Is there easy way to send data from my NotificationNotDisplayingExtender receivedResult to my PusherReceiver?

For now it looks like my PusherReceiver don't fire his onReceive method.

Many thanks for help in advance.

Robson
  • 1,207
  • 3
  • 21
  • 43
  • You should notice this is deprecated since api 26: https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html – user1209216 Mar 08 '18 at 11:40
  • @user1209216 Yep, I know and for newer api I will do update for this, but now I need to find a solution for notifications. :/ – Robson Mar 08 '18 at 11:46
  • 2
    if I understand your question correctly, you just have to stop calling the NotificationManager to stop showing the notification. The notification are only shown when you build them and call notify. Just use your service to process the data without building a notification – emirua Mar 08 '18 at 22:52

4 Answers4

2

There are two types of payload. 1. Data 2. Notification

https://developers.google.com/cloud-messaging/concept-options

Use only data payload. Then you always get the call in FirebaseMessagingService onMessageRececived Method

KKSINGLA
  • 1,284
  • 2
  • 10
  • 22
1

The thing is basically we have two type of notifications.

One which can be called Notification Type, is that the push has a notification object in sent/received bundle, in which you have to handle it when your app is in foreground and the notification is received. In this case, if your app is in foreground, then you can handle it and do whatever you like which is not showing a notification. But if the app is in background, a notification will automatically create by google and it takes predefined title and message objects within the received push bundle to make the notification.

Second type which can be called Data Type, do not have any notification object in the sent/received bundle. In this scenario, your app is in foreground or background, you should handle everything. So, if you put your data in data object of your push notification message, everything will be in your hands.

So, in short, just put your data in data object of your notification and implement your desired logic.

A. Badakhshan
  • 1,045
  • 7
  • 22
1

I do not see the JSON data you are referring to. However, I suppose the update key in your JSON is containing null. In your code you are checking if the JSON data has the key update in it. This function will always return true if the key exists in the JSON body. You might have the field with null value which is indicating that you are not supposed to show the notification in the system tray.

In that case, you might consider using isNull function. It returns true if this object has no mapping for update or if it has a mapping whose value is null.

// Start the service, keeping the device awake while it is launching.
if (!notificationData.isNull("update")) {
    startWakefulService(context, service);
} else {
    // Do nothing
}

And yes, please use the data payload from the notification that you get.

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
  • Hmm, it prevent running wakeful service, but notifications are still displayed. Important thing is that this problem exists only if app is on background/closed. – Robson Mar 12 '18 at 16:09
0

Every time you notify the NotificationManager to show a notification, you provide an ID to be used for the notification to edit or cancel that notification later on. If you show a notification by manager.notify(notificationId, notification), you can cancel it with manager.cancel(notificationId).

If you want to remove all the notifications, you can use NotificationManager.cancelAll().

Adib Faramarzi
  • 3,798
  • 3
  • 29
  • 44
  • Thanks for advice Adib. Canceling notifications works, but it looks weird when user get's notification with vibration, and it's canceled just after receive. I updated my question and I hope only one problem left. – Robson Mar 12 '18 at 16:44
  • 1
    From what I understand you fixed the previous issue, now you have a `BroadcastReceiver` that does not get called and you want to cal it? If that is the case you can call your broad cast receiver like this: ```Intent intent = new Intent("my.action.string"); context.sendBroadcast(intent);```. you need to change the intent action according to your desired receiver. – Adib Faramarzi Mar 12 '18 at 20:51
  • I did it by sending broadcast regarding your advice if notification has update key in `NotificationNotDisplayingExtender` I created an intent and did something like below and it works: `Intent intent = new Intent();` I set action the same like I set in manifest for my intent `intent.setAction("MY_NOTIFICATION");` and after that I added data to my intent and send broadcast `intent.putExtra("data", notificationBody); sendBroadcast(intent);` Thanks, it works! :) – Robson Mar 15 '18 at 11:30
  • @Robson this is way to do so, first you are creating the notification and then removing that – KKSINGLA Mar 15 '18 at 11:46