Android notifications in background

Firebase Notifications in Background & Foreground in Android

When developers need to integrate push notifications in their Android apps, the first thing comes in mind is Firebase Notifications or Firebase Messaging. But when they integrate, there are few common issues which they stuck into. One of those common issues is that the applications doesn’t get push notifications. There are multiple reasons such as Unregistered device token or app is killed or Android Oreo’s doze mode is on etc.

We will talk about here for one reason of app being in background and foreground and see how it can be solved. Firebase Notifications applies different mechanisms when app is foreground and when app is in background.

Handling Notifications in Foreground

When the app is closed, your notifications are processed by the Google Service process, which take care of displaying your notifications as required, including the default click action (opening the app) and the notification icon.

When the app is in foreground, the received messages are processed by the app, and since there’s no logic to handle it, nothing will happen!

To fix this, we need our own FirebaseMessagingService , let’s create one. Create a new class that extends it and implement the onMessageReceived method. Then get the Notification object from the remoteMessage and create your own Android Notification.

Then add the Service in your AndroidManifest.xml

Now if you try again, you will display notifications while your app is in foreground!

In real life, your onMessageReceived content will be slightly more complex, you will want different smart actions depending on the type of notification, you will want to show a nicer large icon (the one that appears on the notification body) and for sure to change the status bar icon.

The problem you have now is that your onMessageReceived is ONLY called when the app is in foreground, if you app if is background, the Google Services will take care of displaying your message.

The solution? don’t use the “notification” message payload and use “data” instead.

Using Data

The last step to solve this foreground/background problem is to ditch the notification object from your message payload.

Rather than sending:

This way, your notifications will be always handled by the app, by your NotificationService, and not by the Google Service process.

You will need to change your code as well to handle the data payload:

Your whole NotificationService will look like this now:

One more advantage of using data instead of notification object is that you can put anything you want in the “data” object. For example a user ID, a URL to an image… any information that you might want to use to build the notification or to pass to the click action. Note that all will be treated as String s. For example,

This difference is also explained in the Handling Messages section of this document: https://firebase.google.com/docs/cloud-messaging/android/receive

Conclusion

Note that if you keep the “notification” object in your payload, it will behave just like before. You need to get rid of the “notification” and only provide the “data” object.

If you liked this article, you can read my new articles below:

Читайте также:  Как полностью сломать андроид

The with() operator in Kotlin

There are times when there’s multiple lines of operations on the same object, and we do it by calling myObject instance everytime we do any operation.

May 18, 2018

Launching Activities using Kotlin DSL

Launching activities in android apps is a common task and different developers use different approaches. Some use the traditional ways of creating Intent bundles and passing them in startActivity() methods along side the Intents.

May 17, 2018

7 years experience. 💻 Creator of various Open Source libraries on Android . 📝 Author of two technical books and 100+ articles on Android. 🎤 A passionate Public Speaker giving talks all over the world.

Источник

android notification in background if app closed?

I am trying to display a notification in the Android notifications bar even if my application is closed.

I’ve tried searching, but I have had no luck finding help.

An example of this is a news application. Even if the phone screen is off or the news application is closed, it can still send a notification for recent news and have it appear in the notification bar.

How might I go about doing this in my own application?

3 Answers 3

You have to build a Service that handles your news and shows notifications when it knows that are new news (Service Doc). The service will run in background even if your application is closed. You need a BroadcastReciever to run the service in background after the boot phase is completed. (Start service after boot).

The service will build your notifications and send them through the NotificationManager.

EDIT: This article may suit your needs

The selected answer is still correct, but only for devices running Android 7 versions and below. As of Android 8+, you can no longer have a service running in the background while your app is idle/closed.
So, it now depends on how you set up your notifications from your GCM/FCM server. Ensure to set it to the highest priority. If your app is in the background or just not active and you only send notification data, the system process your notification and send it to the Notification tray.

Источник

Using Service to run background and create notification

I want my app to start Service when the button is clicked and the Service should run in background to show a notification at a particular time of day. I have the following code to do this. But it shows errors which I don’t understand. I am new to Android and this is my first app using Service. Any help would be appreciated. Thanks in advance.

2 Answers 2

The question is relatively old, but I hope this post still might be relevant for others.

TL;DR: use AlarmManager to schedule a task, use IntentService, see the sample code here;

What this test-application(and instruction) is about:

Simple helloworld app, which sends you notification every 2 hours. Clicking on notification — opens secondary Activity in the app; deleting notification tracks.

When should you use it:

Once you need to run some task on a scheduled basis. My own case: once a day, I want to fetch new content from server, compose a notification based on the content I got and show it to user.

What to do:

First, let’s create 2 activities: MainActivity, which starts notification-service and NotificationActivity, which will be started by clicking notification:

and NotificationActivity is any random activity you can come up with. NB! Don’t forget to add both activities into AndroidManifest.

Then let’s create WakefulBroadcastReceiver broadcast receiver, I called NotificationEventReceiver in code above.

Here, we’ll set up AlarmManager to fire PendingIntent every 2 hours (or with any other frequency), and specify the handled actions for this intent in onReceive() method. In our case — wakefully start IntentService , which we’ll specify in the later steps. This IntentService would generate notifications for us.

Читайте также:  Фитнес для женщин для андроид

Also, this receiver would contain some helper-methods like creating PendintIntents, which we’ll use later

NB1! As I’m using WakefulBroadcastReceiver , I need to add extra-permission into my manifest:

NB2! I use it wakeful version of broadcast receiver, as I want to ensure, that the device does not go back to sleep during my IntentService ‘s operation. In the hello-world it’s not that important (we have no long-running operation in our service, but imagine, if you have to fetch some relatively huge files from server during this operation). Read more about Device Awake here.

Now let’s create an IntentService to actually create notifications.

There, we specify onHandleIntent() which is responses on NotificationEventReceiver‘s intent we passed in startWakefulService method.

If it’s Delete action — we can log it to our analytics, for example. If it’s Start notification intent — then by using NotificationCompat.Builder we’re composing new notification and showing it by NotificationManager.notify . While composing notification, we are also setting pending intents for click and remove actions. Fairly Easy.

Almost done. Now I also add broadcast receiver for BOOT_COMPLETED, TIMEZONE_CHANGED, and TIME_SET events to re-setup my AlarmManager, once device has been rebooted or timezone has changed (For example, user flown from USA to Europe and you don’t want notification to pop up in the middle of the night, but was sticky to the local time 🙂 ).

We need to also register all our services, broadcast receivers in AndroidManifest:

That’s it!

The source code for this project you can find here. I hope, you will find this post helpful.

Источник

How to handle notifications with FCM when app is in either foreground or background

I used firebase to build My project.
It will also use the FCM (firebase cloud message).
But there is a problem.
I can’t handle the FCM (create my custom notificaion) when app is in background.

The official site tutorial said that
case 1: App foreground -> override the «onMessageReceived()» to create your custom notification.
case 2: App background -> System will create the notification directly. We needn’t and can’t do anything. Because it doesn’t trigger the «onMessageReceived()» in this case.

However if I can do nothing when app is background, I can’t create my custom notification. (e.g. After Users click the notification and it will pop up a window to show detail information.)

So how do I handle notifications with FCM when app is in background?

4 Answers 4

There is a bad news.
Google change the Firebase source code in version ‘com.google.firebase:firebase-messaging:11.6.0’.
handelIntent is «public final void method» now. which means we can’t override it .
If you want to use the solution, change the version to be «com.google.firebase:firebase-messaging:11.4.2»

Try my way. It can perfectly work on the project build version is Android 6.0 above(api level 23) and I have tried it already.

The official site said that the notification will be created by system when app is in background. So you can’t handle it by overriding the «onMessageReceived()». Because the «onMessageReceived()» is only triggered when app is in foreground.

But the truth is not. Actually the notificaions (when app is in background) are created by Firebase Library.

After I traced the firebase library code. I find a better way.

Step 1. Override the «handleIntent()» instead of «onMessageReceived()» in FirebaseMessagingService
why:
Because the method will be trigger either app is in foreground or the background. So we can handle FCM message and create our custom notifications in both cases.

Step 2. Parse the message from FCM
how:
If you don’t know the format of the message you set. Print it and try to parse it.
Here is the basic illustration

Step 2. Remove the notifications created by Firebase library when the app is in background
why:
We can create our custom notification. But the notification created by Firebase Library will still be there (Actually it created by «»super.handleIntent(intent)»». There is detail explaination below.). Then we’ll have two notifcations. That is rather weird. So we have to remove the notificaion created by Firebase Library

how (project build level is Android 6.0 above):
Recognize the notifications which we want to remove and get the informaion. And use the «notificationManager.cancel()» to remove them.

Читайте также:  Аналог putty для android

The my whole sample code:

However if I can do nothing when app is background, I can’t create my custom notification. (e.g. After Users click the notification and it will pop up a window to show detail information.)

So how do I handle notifications with FCM when app is in background?

First, you need to create correct message payload that you send to fcm server. Example:

data payload is actual data you want to show as message details after user clicks on notification, notification payload represents how generated notification should look (there are much more attributes possible to set), you don’t need to build notification by yourself, you only need to set it properties here.

To show your activity after user taps on notication, you need to set intent filter corresponding to click_action :

so activity that have above intent filter will be launched automatically when user taps to notification. Last step is to retrieve data when activity is launched after notification tap. It’s pretty easy. Custom data is passed to activity via bundle. Inside onCreate method for your activity do something like that:

All of above is valid if app is not running or it’s in background. If your app is foreground, no notification will be created. Instead, you will receive onMessageReceived() event so you can handle the same data there (I guess you know how).

Источник

set background color to notifications actions in android10

I have achieved this image link by following this article https://medium.com/@dcostalloyd90/show-incoming-voip-call-notification-and-open-activity-for-android-os-10-5aada2d4c1e4 Notification buttons are working fine. Only issue is i am unable to set background color to these action buttons like visible in above article. I want to set green and red color to accept and cancel buttons respectively. How can i achieve this? Check following codes:

1 Answer 1

I hope your question is still relevant. I also ran into this issue, but after some research i decided to not work with a «styled» action (didn’t work as expected) but with a custom notification layout.

And yes, there’s also an option to attach a custom view to the notification, a RemoteViews :

The notificationLayout is created as follows:

Your layout some_layout can be a normal layout like you would create for custom dialogs, fragments or activities. But beware, a layout of a RemoteViews is limited to the following Views and ViewGroups: https://developer.android.com/reference/android/widget/RemoteViews

If you use other Views or ViewGroups than listed in the documentation your notification will simply not be displayed.

Also have an eye on https://developer.android.com/training/notify-user/custom-notification. Here you can find some useful hints why you should use predefined styles for the TextViews you’re using in your layout, to be conform with day- and night mode and not to have white-on-white-text by accident.

And if everything is working fine you can come up with a styled notification like this one:

PS: If you want to create a custom notification for an incoming call (or something like this) and you want your notification to stay open all the time and not to collaps to the tray then add a FullscreenIntent to your notification (https://developer.android.com/training/notify-user/time-sensitive):

And also don’t forget to include the required permission in the manifest:

PPS: As an addition, here’s the full layout of the custom notification:

Источник

Оцените статью