React-native-fcm not pushing notifications for closed app - android

My App was getting notification only when app is open and in background. but i require notifications should reach even app is closed. How could i do this in reactnative using react-native-fcm?
My code was below please refer to it
FCM.getInitialNotification().then(notif=>console.log(notif));
FCM.requestPermissions(); // for iOS
FCM.getFCMToken().then(token => {
console.log(token)
// store fcm token in your server
});
this.notificationListener = FCM.on(FCMEvent.Notification, async (notif) => {
// there are two parts of notif. notif.notification contains the notification payload, notif.data contains data payload
if(notif.local_notification){
//this is a local notification
return;
}
if(notif.opened_from_tray){
//app is open/resumed because user clicked banner
console.log('clicked');
return;
}
this.showLocalNotification(notif);
});
this.refreshTokenListener = FCM.on(FCMEvent.RefreshToken, (token) => {
console.log(token)
// fcm token may not be available on first load, catch it here
});
showLocalNotification(notif) {
FCM.presentLocalNotification({
title: notif.title,
body: notif.body,
priority: "high",
click_action: notif.click_action,
show_in_foreground: true,
local: true
});
}
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<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="com.evollu.react.fcm.FIRLocalMessagingPublisher"/>
<receiver android:enabled="true" android:exported="true" android:name="com.evollu.react.fcm.FIRSystemBootEventReceiver">
<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>
<service android:name="com.evollu.react.fcm.MessagingService" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service android:name="com.evollu.react.fcm.InstanceIdService" android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
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>
<intent-filter>
<action android:name="fcm.ACTION.HELLO" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="XXXXXX"/>
</application>

Your problem is how you are pushing your notification.
The FCM will recognise and popup only notifications which contains the attribute "notification".
If you need the command
this.showLocalNotification(notif);
to show your notification it means your are managing notifications locally, hence, your closed app won't manage it.
As a result, please check how you are sending your notification to the cloud and be sure the event "FCMEvent.Notification" is triggered only if you dont have a "notification" attribute.
Ex:
noteA = {notification: {title: "Notification Title", body:"Notification body"}, data: {optional: "content"}};
noteB = {title: "Notification Title", body:"Notification body"}, data: {optional: "content"}};
Result:
noteA: Should popup a notification without triggering FCMEvent.Notification
noteB: Should trigger FCMEvent.Notification and if this.showLocalNotification(notif) is invoked a local notification will be shown.

Related

React native Receive notification but not show pop-up in android

AndroidManifest.xml
This is My android manifest file, notifications comes properly but not showing popup like other applications. Application is in foreground sate or background state popup is not showing notifications are show in notification tray only.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pushnotificationexample">
<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">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<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" />
<!-- <meta-data android:name="com.dieam.reactnativepushnotification.channel_create_default" android:value="true"/>-->
<!-- 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="true"/>
<!-- 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>
</application>
</manifest>
Firebase Push Notification Listener
messaging().onNotificationOpenedApp(remoteMessage => {
console.log(
'Notification caused app to open from background state:',
remoteMessage.notification,
);
navigation.navigate(remoteMessage.data.type);
});
// Check whether an initial notification is available
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
console.log(
'Notification caused app to open from quit state:',
remoteMessage.notification,
);
setInitialRoute(remoteMessage.data.type); // e.g. "Settings"
}
setLoading(false);
});
Above Listener Will Be Handled When Application Is In Background State OR Killed.
But When Application Is In Foreground Use Code Below
messaging().onMessage(remoteMessage => {
PushNotification.localNotification({
id: "1", ....
// Configure Local Notification
})
}
)
Firebase Referece
Firebase PushNotification PayLoad

Why does FirebaseMessagingService.onMessageReceived() not getting called?

In my android project I'm including Firebase Cloud Messaging. I'm on SDK 21 (Android 5).
My Intention is to override the onMessageReceived() method of MyFirebaseMessagingService to catch the method sent by Firebase and create my own notification.
But it seems like onMessageReceived doesn't get called anyway. I followed the built-in instructions from Android Studio to implement firebase and testing with the firebase console does actually send a message received by my test devices.
So my question is, did I forgot to implement something? I have my custom FirebaseMessagingService, a BroadcastReceiver to implement actions in notifications and an Applicationclass that creates and handles the notification channels for SDKs >= 26.
This is a part of my manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:name=".Networking.Firebase.FireBaseApp"
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=".Activities.MainActivity"/>
<activity
android:name=".Activities.SplashActivity"
android:noHistory="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<service android:name=".Networking.Firebase.PushMessageService" />
<receiver android:name=".Networking.Firebase.PushReceiver"/>
</application>
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(message: RemoteMessage?) {
super.onMessageReceived(message)
//TODO Your Code
}
}
}
<!-- Firebase Notifications Service -->
<service
android:name=".MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!--
Set custom default icon. This is used when no icon is set for incoming notification messages.
-->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_notification" />
<!--
Set color used with incoming notification messages. This is used when no color is set for the incoming
notification message.
-->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
You need two service extends
1. FirebaseMessagingService
2. FirebaseInstanceIdService
and in manifest
<service
android:name="yourClassExtendsFirebaseMessagingService"
android:enabled="true"
android:exported="true"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- [END firebase_service] -->
<!-- [START firebase_iid_service] -->
<service android:name="yourClassExtendsFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
FirebaseInstanceIdService needs to refresh token.
On Android O and above need to ask premisen run an app when it closes on some devices.

cannot receive any push notification on react native android app

I am following this documentation for receiving push notification on react native android https://github.com/evollu/react-native-fcm, I am able to receive the device token id, but I am not able to receive any notification when I am using sending manually from firebase using that device id:
This is the code on my react native app:
import {Platform} from 'react-native';
import FCM, {FCMEvent, RemoteNotificationResult, WillPresentNotificationResult, NotificationType} from 'react-native-fcm';
// this shall be called regardless of app state: running, background or not running. Won't be called when app is killed by user in iOS
FCM.on(FCMEvent.Notification, async (notif) => {
// there are two parts of notif. notif.notification contains the notification payload, notif.data contains data payload
if(notif.local_notification){
//this is a local notification
}
if(notif.opened_from_tray){
//iOS: app is open/resumed because user clicked banner
//Android: app is open/resumed because user clicked banner or tapped app icon
}
// await someAsyncCall();
if(Platform.OS ==='ios'){
//optional
//iOS requires developers to call completionHandler to end notification process. If you do not call it your background remote notifications could be throttled, to read more about it see https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623013-application.
//This library handles it for you automatically with default behavior (for remote notification, finish with NoData; for WillPresent, finish depend on "show_in_foreground"). However if you want to return different result, follow the following code to override
//notif._notificationType is available for iOS platfrom
switch(notif._notificationType){
case NotificationType.Remote:
notif.finish(RemoteNotificationResult.NewData) //other types available: RemoteNotificationResult.NewData, RemoteNotificationResult.ResultFailed
break;
case NotificationType.NotificationResponse:
notif.finish();
break;
case NotificationType.WillPresent:
notif.finish(WillPresentNotificationResult.All) //other types available: WillPresentNotificationResult.None
break;
}
}
});
FCM.on(FCMEvent.RefreshToken, (token) => {
console.log(token)
// fcm token may not be available on first load, catch it here
});
class App extends Component {
componentDidMount() {
// iOS: show permission prompt for the first call. later just check permission in user settings
// Android: check permission in user settings
FCM.requestPermissions().then(()=>console.log('granted')).catch(()=>console.log('notification permission rejected'));
FCM.getFCMToken().then(token => {
console.log(token)
// store fcm token in your server
});
this.notificationListener = FCM.on(FCMEvent.Notification, async (notif) => {
// optional, do some component related stuff
});
// initial notification contains the notification that launchs the app. If user launchs app by clicking banner, the banner notification info will be here rather than through FCM.on event
// sometimes Android kills activity when app goes to background, and when resume it broadcasts notification before JS is run. You can use FCM.getInitialNotification() to capture those missed events.
// initial notification will be triggered all the time even when open app by icon so send some action identifier when you send notification
FCM.getInitialNotification().then(notif => {
console.log(notif)
});
}
componentWillUnmount() {
// stop listening for events
this.notificationListener.remove();
}
Android Manifest file looks as below:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="fi.rogerstudio.possis"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="com.example.healthgps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-feature android:name="android.hardware.location.gps" />
<application
android:name=".MainApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true">
<activity android:name=".MainActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:theme="#style/Theme.Exponent.Light"
android:windowSoftInputMode="adjustResize"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<data android:scheme="exp6a747c4f7f604b89a93d9f3d281cbb77"/>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
</intent-filter>
</activity>
<service
android:name="io.invertase.firebase.messaging.MessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name="io.invertase.firebase.messaging.InstanceIdService" android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<service android:name="com.evollu.react.fcm.MessagingService" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service android:name="com.evollu.react.fcm.InstanceIdService" android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<!-- The Facebook SDK runs FacebookInitProvider on startup and crashes if there isn't an ID here -->
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="fb0"/>
<!-- react-native-background-geolocation licence -->
<meta-data android:name="com.transistorsoft.locationmanager.license" android:value="14ef777231a8412c8b2d109443999356a2c13e62c07e2868345f5e13f01b3c83" />
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="#mipmap/ic_launcher"/>
<receiver android:name="com.evollu.react.fcm.FIRLocalMessagingPublisher"/>
<receiver android:enabled="true" android:exported="true" android:name="com.evollu.react.fcm.FIRSystemBootEventReceiver">
<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>
</application>
</manifest>
I see your current problem is about your installed package. You made some conflict package install.
Please remove io.invertase.firebase.messaging from your app.
npm uninstall react-native-firebase --save
Then you also need to remove from your settings.gradle

App doesn't show firebase notifications (broadcast intent callback: result=CANCELLED forIntent)

I can't receive my Firebase Notifications when the app is killed or in background.
I signed the APK, and it doesn't work, and when I send my Data notification with JSON the logcat shows me this error:
broadcast intent callback: result=CANCELLED forIntent { act=com.google.android.c2dm.intent.RECEIVE pkg=com.example.paolomazza.firebasedemo3 (has extras) }
Given the following Manifest, what could be the cause of this bug?
Thanks in Advance
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<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">
<receiver android:name="com.example.paolomazza.firebasedemo3.OnBootBroadcastReceiver">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".FirebaseIDService">
<intent-filter>
<action android:name="com.example.paolomazza.firebasedemo3.INSTANCE_ID_EVENT"
android:stopWithTask="false" />
</intent-filter>
</service>
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"
android:stopWithTask="false" />
</intent-filter>
</service>
</application>
And here's the code for showing the notifications
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
//you can get your text message here.
String text= data.get("my_custom_key");
System.out.println(text);
notifies(text);
}
private void notifies(String body){
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(MyFirebaseMessagingService.this)
.setSmallIcon(android.R.drawable.ic_menu_help)
.setContentTitle("Congratulations!")
.setContentText(body);
Notification mNot= mBuilder.build();
NotificationManager mNotMan = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
mNotMan.notify(1,mNot);
}
OK, I just solved the problem.
If you're using a Huawei device, or a device that uses a EMOI os, just go to
Advanced settings
than go to
Battery
and
Protected Apps
than select your app, switch it on and you'll be able to receive your notifications in the background!

Push notification from app using parse

i am using parse 1.13.0 in nodechef.com i tried setting my app to send notification but i getting some problems.
This is my Manifest:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.path" >
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.my.path.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.my.path.permission.C2D_MESSAGE" />
<application
android:name=".MainApplication"
android:allowBackup="true"
android:fullBackupContent="true"
android:icon="#drawable/logo"
android:label="#string/app_name"
android:theme="#style/hsfTheme">
<meta-data
android:name="com.parse.APPLICATION_ID"
android:value="#string/parse_app_id" />
<meta-data
android:name="com.parse.CLIENT_KEY"
android:value="#string/parse_client_key" />
<meta-data
android:name="com.parse.push.notification_icon"
android:resource="#drawable/logo" />
<service android:name="com.parse.PushService" />
<receiver android:name="com.parse.ParseBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
<receiver android:name="com.parse.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.my.path" />
</intent-filter>
</receiver>
<!-- activity main. -->
<activity
android:name=".A0"
android:configChanges="keyboardHidden|screenLayout|orientation"
android:immersive="true"
android:screenOrientation="portrait"
android:theme="#style/hsfTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".A1" />
<activity android:name=".A2" />
<activity android:name=".A3" />
<activity android:name=".utils.A4" />
<!-- Include the AdActivity configChanges and theme. -->
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#android:style/Theme.Translucent" />
</application>
in my application class i have: ParseInstallation.getCurrentInstallation().saveInBackground();
DeviceToken is empty in _Installation class
Push not working
All i need is send push notification from my app, in some actions i would like notify all users or some users using Installation channels. Don't care if i will use "parse push" or gcm, just need a simple way to send push notifications from app.
EDIT
Push from parse-dashboard is working now, but i cant send push notification from client. I tried a push and got "unauthorized: enable master key". So what i need to do ?
EDIT 2
I created a cloud code but its looks not working get values from request.params:
Parse.Cloud.define("sendPush", function(request,response) {
var _locale = "en-US";//request.params.locale;
var _message = "test";//request.params.message;
var query = new Parse.Query(Parse.Installation);
query.equalTo("localeIdentifier", _locale);
Parse.Push.send({
data: {
alert: _message,
badge: "Increment",
sound: "default"
},
where: query
}, {
useMasterKey: true
})
.then(function() {
response.success("Push Sent!");
}, function(error) {
response.error("Error while trying to send push " + error.message);
});
});
EDIT 3
HashMap<String,String> map = new HashMap<String, String>();
map.put("locale","en-US");
map.put("message","Text added");
ParseCloud.callFunctionInBackground("sendPush",map, new FunctionCallback<Object>() {
#Override
public void done(Object object, ParseException e) {
// toast done
}
});
after investigate it a bit i noticed that in order to send push you must create cloud code function and use your master key (by sending userMasterKey=true parameter to the send push function.
I describe my answer in here so please go through the steps and it should work for you.

Categories

Resources