I have this problem, I am creating an android application that is connected to Firebase. Then I have my Raspberry Pi connected to Firebase, the data sent from the Pi is GPS coordinates specifically latitude and longitude. The main application that I want to create has a Push Notification function when data on the Firebase has been changed or the coordinates on the main node has been changed. Here is the screenshot of my Firebase Data:
Firebase Database Screenshot
My problem is this, the cloud function that I created has found errors that I don't understand or I'm just overseeing it. I've looked up in the Firebase documentation, sample codes from articles and I guess nothing just seemed to work for me. Here is the code for the cloud function and the error I got when I just manually type in data in Firebase.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendLocationNotification = functions.database.ref("/GPS/{gps_id}").onWrite((event)=>{
var latitude = event.data.child('latitude');
var longitude = event.data.child('longitude');
if(!latitude.changed() && !longitude.changed()){
return console.log('The database has been reset');
}
const payload = {
notification:{
title: "Location Monitor",
body: "Your motorcycle has moved",
icon: "default",
sound: "default"
}
};
const options = {
priority: "high",
timeToLive: 60 * 60 * 24
};
return admin.messaging().sendToTopic("Location_Notification", payload, options)
});
The next one is with the Android Application, even though my Firebase FCM is in the gradle:app, then I manually send a message in the Firebase console, the application doesn't receive any messages on the avd or phone installed with the app. Here's a code for my MessagingService to handle foreground notifications:
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import java.util.Map;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FirebaseMessgingService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage){
if(remoteMessage.getData().size()>0){
Map<String, String> payload = remoteMessage.getData();
showNotification(payload);
}
}
private void showNotification(Map<String, String> payload) {
Intent intent = new Intent(this, Tracking.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setSmallIcon(R.drawable.track)
.setContentIntent(pendingIntent)
.setContentTitle(payload.get("Title"))
.setContentText(payload.get("Body"))
.setSound(defaultSoundUri);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
Then here's my android manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Menu" />
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/track"/>
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<activity
android:name=".Tracking"
android:label="#string/title_activity_tracking" />
<activity
android:name=".Tracing"
android:label="#string/title_activity_tracing" />
<activity android:name=".Tips" />
<activity android:name=".Instruction" />
<activity android:name=".About"></activity>
</application>
</manifest>
This is my gradle:app
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId ""
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.google.android.gms:play-services-maps:11.0.4'
implementation 'com.google.firebase:firebase-database:11.0.4'
implementation 'com.google.firebase:firebase-messaging:11.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
compile 'com.github.Hitomis:CircleMenu:v1.1.0'
}
apply plugin: 'com.google.gms.google-services'
Here's a the error that keeps on appearing:
TypeError: Cannot read property 'child' of undefined
at exports.sendLocationNotification.functions.database.ref.onWrite (/user_code/index.js:13:30)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:700:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
As per the Firebase documentation for the onWrite method, it's passed:
a functions.Change containing a non-null functions.database.DataSnapshot and an optional non-null
functions.EventContext)
However in your function you're expecting an event object, which results empty.
Following the sample code available here, you could re-write your function like so:
exports.makeUppercase = functions.database.ref("/GPS/{gps_id}")
.onWrite((change, context) => {
// You can get the previous value for latitude and longitude
var previousLatitude = change.before.ref.parent.child('latitude');
var previousLongitude = change.before.ref.parent.child('longitude');
// And the new values
var newLatitude = change.after.ref.parent.child('latitude');
var newLongitude = change.after.ref.parent.child('longitude');
// And perform your logic from here
...
return admin.messaging().sendToTopic("Location_Notification", payload, options);
});
I haven't checked the Android issue you mentioned but I guess that since the Firebase Function was failing, the return statement didn't execute and no notification was sent at all.
Related
I've recently set up push notifications in my React Native app and it's working fine in iOs, but failing to pop up in Android. Here is the function that I'm calling to trigger the notification.
function pushNotif(){
PushNotification.localNotification({
channelId: "specialid", // (required) channelId, if the channel doesn't exist, notification will not trigger.
title: "hello",
message: "test message"
})
}
and here is where I configure the push notification above
// Must be outside of any component LifeCycle (such as `componentDidMount`).
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function (token) {
console.log("TOKEN:", token);
},
// (required) Called when a remote is received or opened, or local notification is opened
onNotification: function (notification) {
console.log("NOTIFICATION:", notification);
// process the notification
// (required) Called when a remote is received or opened, or local notification is opened
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// (optional) Called when Registered Action is pressed and invokeApp is false, if true onNotification will be called (Android)
onAction: function (notification) {
console.log("ACTION:", notification.action);
console.log("NOTIFICATION:", notification);
// process the action
},
// (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
onRegistrationError: function(err) {
console.error(err.message, err);
},
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true,
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
* - if you are not using remote notification or do not have Firebase installed, use this:
* requestPermissions: Platform.OS === 'ios'
*/
requestPermissions: true,
});
As I said it's working fine on iOS, and when I remove the channelId (which I know is required for android) I get this message...
No Channel ID Passed. Notification may not work
This leads me to believe it's being configured somehow but not fully.
Here are the rest of my configuration files after following this: https://github.com/zo0r/react-native-push-notification
In android/build.gradle
buildscript {
ext {
googlePlayServicesVersion = "+" // default: "+"
firebaseMessagingVersion = "+" // default: "21.1.0"
buildToolsVersion = "29.0.3"
minSdkVersion = 21
compileSdkVersion = 30
targetSdkVersion = 30
ndkVersion = "20.1.5948944"
}
repositories {
google()
jcenter()
}
dependencies {
classpath("com.android.tools.build:gradle:4.1.0")
classpath 'com.google.gms:google-services:4.3.10'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
In android/app/src/main/AndroidManifest.xml
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:roundIcon="#mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="#style/AppTheme">
<!-- Change the value to true to enable pop-up for in foreground on receiving remote notifications (for prevent duplicating while showing local notifications set this to false) -->
<meta-data android:name="com.dieam.reactnativepushnotification.notification_foreground"
android:value="false"/>
<!-- Change the resource name to your App's accent color - or any other color you want -->
<meta-data android:name="com.dieam.reactnativepushnotification.notification_color"
android:resource="#color/white"/> <!-- or #android:color/{name} to use a standard color -->
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
<service
android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
...
In android/app/src/main/java/com/{app_name}/MainActivity.java
...
import com.facebook.react.ReactActivity;
import android.content.Intent;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
#Override
protected String getMainComponentName() {
return "cjcChatApp";
}
}
How can I get this to work on Android?
i think you forgot for create chanel, you can try this :
function pushNotif(){
PushNotification.createChannel(
{
channelId: "specialid", // (required)
channelName: "Special messasge", // (required)
channelDescription: "Notification for special message", // (optional) default: undefined.
importance: 4, // (optional) default: 4. Int value of the Android notification importance
vibrate: true, // (optional) default: true. Creates the default vibration patten if true.
},
(created) => console.log(`createChannel returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
);
PushNotification.localNotification({
channelId:'specialid', //his must be same with channelid in createchannel
title:'hello',
message:'test message'
})
}
Recently I upgraded to firebase_messaging: ^10.0.0 When app is in not running and if notification comes it is displaying twice. I modified the notification data in code after receiving and displayed it. Even then I can see the modified and non modified notifications. I don't know where that notification is triggering. But when app is running it is displaying notification once only(works fine). Here goes my code
/*main.dart*/
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
//await Firebase.initializeApp();
// await HomePageState.handleMessage(message);
String title="${message.notification!.title}";
String body="${message.notification!.body}";
_flutterLocalNotificationsPlugin.show(0, title, body, platformChannelSpecifics, payload: jsonEncode(message.data));
AppDatabase database= await $FloorAppDatabase.databaseBuilder(Constants.dataBaseName).addMigrations([migration1to2]).build();
if(!title.toLowerCase().contains("cancelled")){
var date=DateFormat("dd-MMM-yyyy hh:mm aa").format(DateTime.now());
NotificationModel notification=NotificationModel(title: title,message: body,read: 0,date: date);
await database.notificationDao.insertNotification(notification);
}
print("Handling a background message: ${message.messageId}");
}
Future<void> main() async {
//this line make sure all the required widgets are loaded before main application starts
//SharedPreferences.setMockInitialValues({});
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
var initializationSettingsAndroid = new AndroidInitializationSettings('#mipmap/ic_notification');
var initializationSettingsIOS = new IOSInitializationSettings(onDidReceiveLocalNotification: onDidReceiveLocalNotification);
//var initializationSettings = new InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
var initializationSettings = new InitializationSettings(android: initializationSettingsAndroid,iOS: initializationSettingsIOS);
_flutterLocalNotificationsPlugin.initialize(initializationSettings,onSelectNotification: onSelectingNotification);
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
//Initializing repository and carrying forward to avoid multiple instances of database
Repository _repository = Repository();
// runApp(BlocProvider(
// create: (_) => ThemeBloc()..add(ThemeLoadStarted()),
// child: MyApp(
// repository: _repository,
// ),
// ));
SentryOptions options=SentryOptions(dsn: APIs.sentryAPI);
final SentryClient _sentry = SentryClient(options);
Future<void> _reportErrorToSentry(dynamic error, dynamic stackTrace) async {
// Print the exception to the console.
print('Caught error: $error');
await _sentry.captureException(
error,
stackTrace: stackTrace,
);
}
runZonedGuarded(() async{
// runApp(BlocProvider(
// create: (_) => ThemeBloc()..add(ThemeLoadStarted()),
// child: MyApp(
// repository: _repository,
// ),
// ));
await SentryFlutter.init(
(options) => options.dsn = APIs.sentryAPI,
appRunner: () => runApp(BlocProvider(
create: (_) => ThemeBloc()..add(ThemeLoadStarted()),
child: MyApp(
repository: _repository,
),
)),
);
}, (error, stackTrace) {
print('runZonedGuarded: Caught error in my root zone.');
FirebaseCrashlytics.instance.recordError(error, stackTrace);
_reportErrorToSentry(error,stackTrace);
});
}
Application.kt
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingBackgroundService
class Application : FlutterApplication(), PluginRegistrantCallback {
override fun registerWith(registry: PluginRegistry) {
//FirebaseCloudMessagingPluginRegistrant.registerWith(registry)
FlutterLocalNotificationPluginRegistrant.registerWith(registry)
SqflitePluginRegistrant.registerWith(registry)
}
}
FirebaseCloudMessagingPluginRegistrant.kt which I commented out in application.kt
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingPlugin
class FirebaseCloudMessagingPluginRegistrant {
companion object {
fun registerWith(registry: PluginRegistry) {
if (alreadyRegisteredWith(registry)) {
return
}
FlutterFirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
}
fun alreadyRegisteredWith(registry: PluginRegistry): Boolean {
val key = FirebaseCloudMessagingPluginRegistrant::class.java.name
if (registry.hasPlugin(key)) {
return true
}
registry.registrarFor(key)
return false
}
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="**.***.***tomer">
<!-- io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />-->
<!-- android:label="#string/app_label"-->
<application
android:name=".Application"
android:label="Zuzu"
android:usesCleartextTraffic="true"
android:networkSecurityConfig="#xml/network_security_config"
android:icon="#mipmap/ic_launcher">
<meta-data android:name="io.flutter.network-policy"
android:resource="#xml/network_security_config"/>
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize"
tools:targetApi="n">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="#style/NormalTheme"
/>
<!-- Displays an Android View that continues showing the launch screen
Drawable until Flutter paints its first frame, then this splash
screen fades out. A splash screen is useful to avoid any visual
gap between the end of Android's launch screen and the painting of
Flutter's first frame. -->
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="#drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyBqZ4aa************GMzHpofWKeEU"/>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/facebook_app_id"/>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="Zuzu" />
<meta-data android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#mipmap/ic_notification"/>
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/notification"/>
<activity
android:name="com.yalantis.ucrop.UCropActivity"
android:screenOrientation="portrait"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"/>
</application>
</manifest>
This issue is in android only that too when app is not running. Where am I doing wrong?
It appears you're sending a "notification" message from Firebase Messaging when you should be sending a "data" message.
Here is the difference between a notification message and a data message:
Notification message
FCM automatically displays the message to end-user devices on behalf
of the client app.
Data message
Client app is responsible for processing data messages.
About FCM Messages | Firebase (#Message types)
That explains why you get the unmodified version of the notification (this is from the automatic display of the notification message) and the modified version of the notification (this is from your own code where you handle the notification).
Solution:
You need to send a data message from your backend.
So if you had this before as your notification payload:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}
}
you should change it to:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}
}
Just created a new Flutter app
Ultimately trying to open my app or show a full screen Activity when I receive a notification (think phone call)
Currently just trying to console log in a native class called through the background message handler
Receiving this error when I send the notification, do you see what I'm doing wrong? Is there a different way I should approach this?
D/FLTFireMsgReceiver(17161): broadcast received for message
W/com.myapp(17161): Accessing hidden method Landroid/os/WorkSource;->add(I)Z (greylist,test-api, reflection, allowed)
W/com.myapp(17161): Accessing hidden method Landroid/os/WorkSource;->add(ILjava/lang/String;)Z (greylist,test-api, reflection, allowed)
W/com.myapp(17161): Accessing hidden method Landroid/os/WorkSource;->get(I)I (greylist, reflection, allowed)
W/com.myapp(17161): Accessing hidden method Landroid/os/WorkSource;->getName(I)Ljava/lang/String; (greylist, reflection, allowed)
I/flutter (17161): FlutterFire Messaging: An error occurred in your background messaging handler:
I/flutter (17161): MissingPluginException(No implementation found for method getBatteryLevel on channel samples.flutter.dev/battery)
main.dart
...
Future<void> backgroundHandler(RemoteMessage message) async {
const platform = const MethodChannel('samples.flutter.dev/battery');
String response = "";
try {
final int result = await platform.invokeMethod('getBatteryLevel');
response = "Response: $result";
} on PlatformException catch (e) {
response = "Failed to Invoke: '${e.message}'.";
}
print(response);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(backgroundHandler);
runApp(MyApp());
}
...
MainActivity.kt
class MainActivity: FlutterActivity() {
private val CHANNEL = "samples.flutter.dev/battery"
override fun configureFlutterEngine(#NonNull flutterEngine: FlutterEngine) {
Log.i(">>BLOOP", "inside configureFlutterEngine")
GeneratedPluginRegistrant.registerWith(flutterEngine);
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
call, result ->
// Note: this method is invoked on the main thread
Log.i(">>BLOOP", "call looking for method: ${call.method}");
if(call.method == "getBatteryLevel") {
result.success(1);
} else {
result.notImplemented()
}
}
}
}
AndroidManifest.xml
...
</activity>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="samples.flutter.dev/battery" />
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
Things I've tried:
flutter clean flutter run
Uninstalling/Reinstalling the app on the phone
Reverting Android Gradle Plugin Version to 3.5.1
Adding android/app/src/proguard-rules.pro with -keep class androidx.lifecycle.DefaultLifecycleObserver
Using a different channel than the one I set in the manifest
platform.invokeMethod() from a button click inside the app, it does work from the app UI
I was unable to register a native MethodCall function the background handler could invoke. Instead I found 2 solutions:
Capture the message natively
Use flutter-local-notifications and streams
I ended up going with solution 2 due to better platform support and it being less hacky
I'm only going to show android implementations
(option 1) Capture the message natively
Install firebase-messaging
// android/app/build.gradle
...
dependencies {
...
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.google.firebase:firebase-messaging:21.1.0' <-- THIS ONE
}
Create a background service
// android/app/src/main/kotlin/<project>/BackgroundService.kt
class BackgroundService: FirebaseMessagingService() {
// Function triggered when we receive a message (as specified in AndroidManifest.xml
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
// Waking the screen for 5 seconds and disabling keyguard
val km = baseContext.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
val kl = km.newKeyguardLock("MyKeyguardLock")
kl.disableKeyguard()
val pm = baseContext.getSystemService(Context.POWER_SERVICE) as PowerManager
val wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.ON_AFTER_RELEASE, TAG)
wakeLock.acquire(5000L)
// Create an intent to launch .MainActivity and start it as a NEW_TASK
val notificationIntent = Intent("android.intent.category.LAUNCHER")
notificationIntent
.setAction(Intent.ACTION_MAIN)
.setClassName("com.myapp", "com.myapp.MainActivity")
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(notificationIntent)
}
}
Register permissions and the BackgroundService to receive firebase message events
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myapp">
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
...
</activity>
<service android:name=".BackgroundService" android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
(option 2) Use flutter-local-notifications and streams
Install flutter deps
# pubspec.yaml
...
dependencies:
flutter:
sdk: flutter
firebase_core: ^1.0.4
firebase_messaging: ^9.1.2
flutter_local_notifications: ^5.0.0+3
rxdart: ^0.26.0
...
Register permissions
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
...
<activity
...
android:showWhenLocked="true"
android:turnScreenOn="true">
Top level initialization in main.dart
// We use this to `show` new notifications from the app (instead of from firebase)
// You'll want to be sending high priority `data` messages through fcm, not notifications
final FlutterLocalNotificationsPlugin localNotifications = FlutterLocalNotificationsPlugin();
// Uses rxdart/subjects to trigger showing a different page in your app from an async handler
final BehaviorSubject<String> selectNotificationSubject = BehaviorSubject<String>();
FCM message handler in main.dart
// handler function for when we receive a fcm message
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// build out and show notification using flutter-local-notifications
const AndroidNotificationDetails androidSpecifics = AndroidNotificationDetails(
"channel_id", "channel_name", "Test bed for all dem notifications",
importance: Importance.max, priority: Priority.max, fullScreenIntent: true, showWhen: true);
const NotificationDetails platformSpecifics = NotificationDetails(android: androidSpecifics);
// The notification id should be unique here
await localNotifications.show(DateTime.now().second, "Plain title", "Plain body", platformSpecifics,
payload: "item x");
}
entrypoint function in main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// if the notification launched the app then show alert page
final NotificationAppLaunchDetails launchDetails = await localNotifications.getNotificationAppLaunchDetails();
String initialRoute = launchDetails.didNotificationLaunchApp ?? false ? ShowAlert.routeName : Home.routeName;
// initialize `flutter-local-notifications`, app_icon needs to be added as a drawable resource
const AndroidInitializationSettings androidSettings = AndroidInitializationSettings("app_icon");
final InitializationSettings initializationSettings = InitializationSettings(android: androidSettings);
await localNotifications.initialize(initializationSettings, onSelectNotification: (String payload) async {
// Will be called when activity is shown from notification, here we can trigger showing our alert page
initialRoute = ShowAlert.routeName;
selectNotificationSubject.add(payload);
});
// Catch firebase messages with our handler function, which will then build and show a notification
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
runApp(
MaterialApp(
initialRoute: initialRoute,
routes: <String, WidgetBuilder>{
Home.routeName: (_) => Home(),
ShowAlert.routeName: (_) => ShowAlert(),
},
),
);
}
Home widget in main.dart
// Needs to be stateful so we can use lifecycle methods for the notification stream changes and navigation
class Home extends StatefulWidget {
static const String routeName = "/home";
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
void initState() {
super.initState();
// when onSelectNotification is called, our new payload will trigger this function
selectNotificationSubject.stream.listen((String payload) async {
await Navigator.pushNamed(context, ShowAlert.routeName);
});
}
#override
void dispose() {
selectNotificationSubject.close();
super.dispose();
}
...
Im using react-native-firebase in my app for cloud messanging + notification. it get all body and data when app is in use but it cant get anything when app is closed or in background ....
I tried Headless JS but thats also not working
when i click on notification and when it open's the app its shows this {"google.priority":"high"}
thnaks in advance....
this is my android mainfest
<application
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:allowBackup="false"
android:theme="#style/AppTheme"
android:largeHeap="true">
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_stat_ic_notification" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!---firebase -->
<service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- <meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/> -->
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
<!---firebase end-->
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>
this is my componentdidmount() function
async componentDidMount() {
this.getValueLocally();
requestCameraLOCATION()
const notificationOpen: NotificationOpen = await firebase.notifications().getInitialNotification();
if (notificationOpen) {
const action = notificationOpen.action;
const notification: Notification = notificationOpen.notification;
var seen = [];
alert(JSON.stringify(notification.data, function(key, val) {
if (val != null && typeof val == "object") {
if (seen.indexOf(val) >= 0) {
return;
}
seen.push(val);
}
return val;
}));
}
const channel = new firebase.notifications.Android.Channel('test-channel', 'Test Channel', firebase.notifications.Android.Importance.Max)
.setDescription('My apps test channel');
// Create the channel
firebase.notifications().android.createChannel(channel);
this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification: Notification) => {
// Process your notification as required
// ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
});
this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
// Process your notification as required
notification
.android.setChannelId('test-channel')
.android.setSmallIcon('ic_launcher');
firebase.notifications()
.displayNotification(notification);
});
this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
// Get the action triggered by the notification being opened
const action = notificationOpen.action;
// Get information about the notification that was opened
const notification: Notification = notificationOpen.notification;
var seen = [];
alert(JSON.stringify(notification.data, function(key, val) {
if (val != null && typeof val == "object") {
if (seen.indexOf(val) >= 0) {
return;
}
seen.push(val);
}
return val;
}));
firebase.notifications().removeDeliveredNotification(notification.notificationId);
});
}
async checkPermission() {
firebase.messaging().hasPermission()
.then(enabled => {
if (enabled) {
this.getToken();
} else {
this.requestPermission();
}
});}
async getToken() {
let fcmToken = await AsyncStorage.getItem('fcmToken');
if (!fcmToken) {
fcmToken = await firebase.messaging().getToken();
if (fcmToken) {
// user has a device token
await AsyncStorage.setItem('fcmToken', fcmToken);
}
}
}
async requestPermission() {
firebase.messaging().requestPermission()
.then(() => {
this.getToken();
})
.catch(error => {
console.warn(error);
});
}
and this is my bgMessaging.js
import firebase from 'react-native-firebase';
import type { RemoteMessage } from 'react-native-firebase';
import type { Notification,NotificationOpen} from 'react-native-firebase';
export default async (message: RemoteMessage) => {
const newNotification = new firebase.notifications.Notification()
.android.setChannelId(message.data.channelId)
.setNotificationId(message.messageId)
.setTitle(message.data.title)
.setBody(message.data.body)
.setSound("default")
.setData(message.Data)
.android.setAutoCancel(true)
.android.setSmallIcon('ic_notification')
.android.setCategory(firebase.notifications.Android.Category.Alarm)
// Build a channel
const channelId = new firebase.notifications.Android.Channel(message.data.channelId, channelName, firebase.notifications.Android.Importance.Max);
// Create the channel
firebase.notifications().android.createChannel(channelId);
firebase.notifications().displayNotification(newNotification)
return Promise.resolve();
}
there are two types of messages:
notification + data messages that will be handled by the FCM while in the background (so your code will not have access to the notification), and will call onNotification while in the foreground,
data-only messages will call headlessjs while in the background/closed and will call onMessage while in the foreground.
note: if you remove the title and body, your message will be categorized as the second one. also, data is optional in the first category.
to recap:
for data-only messages:
App in foreground : onMessage triggered
App in background/App closed : Background Handler (HeadlessJS)
for notification + data messages:
App in foreground : onNotification triggered
App in background/App closed : onNotificationOpened triggered if the notification is tapped
for more information and for iOS read the official docs for data-only messages and notification+data messages
It seems that RN firebase did not support this functionality on Android.
Please refer below:
https://rnfirebase.io/docs/v5.x.x/notifications/receiving-notifications#4)-Listen-for-a-Notification-being-opened
On Android, unfortunately there is no way to access the title and body of an opened remote notification. You can use the data part of the remote notification to supply this information if it's required.
I'm trying to show push notification when app is closed so I'm setting up the push notification with react-native-firebase with this docs
I set AndroidManifest.xml as described in docs
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.moonsite.sqlivetrivia"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="22" />
<application
android:name=".MainApplication"
android:allowBackup="true"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:theme="#style/AppTheme">
<receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
<receiver android:enabled="true" android:exported="true" android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_stat_ic_notification" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
<!--
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/> -->
<service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:windowSoftInputMode="adjustResize"
android:launchMode="singleTop"
>
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>
</manifest>
then I wrote the code in react native
import React, { Component } from 'react'
import { View } from 'react-native'
import { Input, Text, Button } from '../Components'
import type { RemoteMessage } from 'react-native-firebase'
import firebase from 'react-native-firebase'
import type { Notification, NotificationOpen } from 'react-native-firebase';
export default class TestComponent extends Component {
async componentDidMount() {
await this.SetUpAuth();
await this.SetUpMessaging();
this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
// Get the action triggered by the notification being opened
const action = notificationOpen.action;
// Get information about the notification that was opened
const notification: Notification = notificationOpen.notification;
});
const notificationOpen: NotificationOpen = await firebase.notifications().getInitialNotification();
if (notificationOpen) {
console.log(notificationOpen)
// App was opened by a notification
// Get the action triggered by the notification being opened
const action = notificationOpen.action;
// Get information about the notification that was opened
const notification: Notification = notificationOpen.notification;
}
}
componentWillUnmount() {
}
async SetUpAuth() {
const credential = await firebase.auth().signInAnonymouslyAndRetrieveData();
if (credential) {
console.log('default app user ->', credential.user.toJSON());
} else {
console.error('no credential');
}
}
async SetUpMessaging() {
this.notification2 = new firebase.notifications.Notification()
.setNotificationId('notificationId')
.setTitle('My notification title')
.setBody('My notification body')
.android.setChannelId('test')
.android.setClickAction('action')
.setData({
key1: 'value1',
key2: 'value2',
});
this.notification2
.android.setChannelId('channelId')
.android.setSmallIcon('ic_launcher');
console.log('assa')
onTokenRefreshListener = firebase.messaging().onTokenRefresh(fcmToken => {
console.log('token generated ->', fcmToken);
// store.dispatch(DeviceActions.SetFCMToken(fcmToken));
});
const fcmToken = await firebase.messaging().getToken();
if (fcmToken) {
// user has a device token
console.log('has token ->', fcmToken);
console.log(firebase.auth().currentUser._user)
firebase.database().ref(`/users/${firebase.auth().currentUser._user.uid}`).set({ pushToken: fcmToken })
// store.dispatch(DeviceActions.SetFCMToken(fcmToken));
} else {
// user doesn't have a device token yet
console.error('no messaging token');
}
const messagingEnabled = await firebase.messaging().hasPermission();
if (messagingEnabled) {
// user has permissions
console.log('User has FCM permissions');
} else {
// user doesn't have permission
console.log('User does not have FCM permissions');
await this.RequestMessagePermissions();
}
messageListener = firebase.messaging().onMessage((message: RemoteMessage) => {
console.log(`Recieved message - ${JSON.stringify(message)}`);
});
notificationDisplayedListener = firebase
.notifications()
.onNotificationDisplayed(notification => {
// Process your notification as required
// ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
console.log(`Recieved notification 1`);
});
notificationListener = firebase
.notifications()
.onNotification(notification => {
console.log(notification)
firebase.notifications().displayNotification(this.notification2)
// Process your notification as required
console.log(`Recieved notification 2`);
});
}
async RequestMessagePermissions() {
console.log('request')
console.log('Requesting FCM permission');
await firebase
.messaging()
.requestPermission()
.catch(err => console.err(err));
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
</View>
)
}
}
then I created firebase http function just for test
export const sendNotification = functions.https
.onRequest(async (req, res) => {
try {
const { token } = req.query;
let tokens = 'fyTfgNZAUBA:APA91bGnx9Vp9MwRA4ohVKcNOM8d5s4a4TXdtI0KTSzcWEgZX1WoLGpofcVQFTCdSbnbqObkukzJEXF3cbmvENYD5pr2MrukjqUNy_bclDuM3rJsV5iSU1vWywL2ZVijJ3s0E9GNfRRe'
var payload = {
notification: {
title: 'Urgent action needed!',
body: 'Urgent action is needed to prevent your account from being disabled!',
sound: 'default',
color: '#84B2D9',
icon: 'ic_notification',
click_action: 'OPEN_MAIN_ACTIVITY'
}
};
// Set the message as high priority and have it expire after 24 hours.
var options = {
priority: 'high',
timeToLive: 60 * 60 * 24
};
console.log('token',token)
let d = await admin.messaging().sendToDevice(tokens, payload,options);
return res.status(200).send({ success: d})
} catch (e) {
console.info(e)
return res.status(400).send({ error: 0 })
}
})
in the response from http function I get success(as you can see here)
{
"success": {
"results": [
{
"messageId": "0:1525112032423298%a0cec506a0cec506"
}
],
"canonicalRegistrationTokenCount": 0,
"failureCount": 0,
"successCount": 1,
"multicastId": 5934848553304349000
}
}
and in my debugger in console log I get the notification as I want
but the issue I don't get push notification when app is closed. I want to get any notification when I'm not into the app.
in addition when I use to display the notification when I get any notification
notificationListener = firebase
.notifications()
.onNotification(notification => {
console.log(notification)
firebase.notifications().displayNotification(this.notification2)
// Process your notification as required
console.log(`Recieved notification 2`);
});
}
so it not display my details here
this.notification2 = new firebase.notifications.Notification()
.setNotificationId('notificationId')
.setTitle('My notification title')
.setBody('My notification body')
.android.setChannelId('test')
.android.setClickAction('action')
.setData({
key1: 'value1',
key2: 'value2',
});
so do i need to save it on state and then in title to display the data?