'Start Background service when app is in background
How can I start an alarm using background services when we receive notification ? When my application is active then background service start easily, but when application is on background then background services can't run.
Solution 1:[1]
1. Why is this happening?
There are two types of messages in FCM (Firebase Cloud Messaging):
Display Messages: These messages trigger the onMessageReceived() callback only when your app is in foreground
Data Messages: Theses messages trigger the onMessageReceived() callback even if your app is in foreground/background/killed
override fun onMessageReceived(remoteMessage: RemoteMessage) {
// ...
// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be:
Log.d(TAG, "From: ${remoteMessage.from}")
// Check if message contains a data payload.
if (remoteMessage.data.isNotEmpty()) {
Log.d(TAG, "Message data payload: ${remoteMessage.data}")
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
scheduleJob()
} else {
// Handle message within 10 seconds
handleNow()
}
}
// Check if message contains a notification payload.
remoteMessage.notification?.let {
Log.d(TAG, "Message Notification Body: ${it.body}")
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nader Gharibian Fard |