I am using react-native-notifications library to implement notification in my app with message cloud firebase , I have followed all guidelines in the documentation,
For react-native-notifications library
For firebase cloud messaging
So when I go to firebase counsel and send a test notification message, nothing happened the app just closed or could call it crash, I have added firebase-analytics to help me with debug what the problem and this what I got when I sent test notification message:
Fatal Exception: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/util/zzq;
at com.google.android.gms.gcm.GcmReceiver.onReceive()
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3177)
at android.app.ActivityThread.-wrap18(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1653)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
here is my code:
import React from 'react'
import { Platform, View } from 'react-native'
import { Notifications } from 'react-native-notifications'
export default class PushNotificationManager extends React.Component {
componentDidMount() {
this.registerDevice()
this.registerNotificationEvents()
}
registerDevice = () => {
Notifications.events().registerRemoteNotificationsRegistered(event => {
// TODO: Send the token to my server so it could send back push notifications...
console.log('Device Token Received', event.deviceToken)
})
Notifications.events().registerRemoteNotificationsRegistrationFailed(event => {
console.error(event)
})
Notifications.registerRemoteNotifications()
}
registerNotificationEvents = () => {
Notifications.events().registerNotificationReceivedForeground((notification, completion) => {
console.log('Notification Received - Foreground', notification)
})
// Calling completion on iOS with `alert: true` will present the native iOS inApp notification.
completion({ alert: false, sound: false, badge: false })
})
Notifications.events().registerNotificationOpened((notification, completion) => {
console.log('Notification opened by device user', notification)
console.log(`Notification opened with an action identifier: ${notification.identifier}`)
completion()
})
Notifications.events().registerNotificationReceivedBackground((notification, completion) => {
console.log('Notification Received - Background', notification)
// Calling completion on iOS with `alert: true` will present the native iOS inApp notification.
completion({ alert: true, sound: true, badge: false })
})
Notifications.getInitialNotification()
.then(notification => {
console.log('Initial notification was:', notification || 'N/A')
})
.catch(err => console.error('getInitialNotifiation() failed', err))
}
render() {
const { children } = this.props
return <View style={{ flex: 1 }}>{children}</View>
}
}
in console.log it consoling the token and in
Notifications.getInitialNotification()
.then(notification => {
console.log('Initial notification was:', notification || 'N/A')
})
it keep consoling 'N/A'
and I wrapped the previous code with the whole app root:
<PaperProvider theme={theme}>
<AuthContext.Provider value={authContext}>
/* here*/ <PushNotificationManager>
<NavigationContainer theme={theme}>
<RootStackScreen />
</NavigationContainer>
/* here*/ </PushNotificationManager>
</AuthContext.Provider>
</PaperProvider>
Related
I have an Ionic 5 app with Capacitor 3 and I'm trying to receive notifications using Firebase Cloud messaging, on an Android device. I followed the configurations,(I downloaded the google JSON file and put my app id name correctly ) and I'm getting correctly the device token. Once my app is open I get the token successfully without any error and then I send a notification sharing my token to the Firebase test message, the notification never arrived, and also I never get an error of push notification in my logger. This is the code that I use for push notification.
export class PushNotificationsService {
constructor(private readonly http: HttpClient, private notificationState: NotificationsStore) { }
public initPush() {
if (Capacitor.getPlatform() !== 'web') {
this.registerPush();
}
}
private registerPush() {
PushNotifications.requestPermissions().then(async result => {
if (result.receive === 'granted') {
// Register with Apple / Google to receive push via APNS/FCM
console.log('granted');
await PushNotifications.register();
} else {
// Show some error
console.log('errorr');
}
});
// On success, we should be able to receive notifications
PushNotifications.addListener('registration',
(token: Token) => { (I get through this step and access the token successfully)
console.log('Push registration success, token: ' + token.value);
this.notification state.setToken(token.value);
}
);
// I never get this step error
PushNotifications.addListener('registrationError',
(error: any) => {
console.log('Error on registration: ' + JSON.stringify(error));
}
);
PushNotifications.addListener('pushNotificationReceived',
(notification: PushNotificationSchema) => {
console.log('Push received: ' + JSON.stringify(notification));
}
);
PushNotifications.addListener('pushNotificationActionPerformed',
(notification: ActionPerformed) => {
console.log('Push action performed: ' + JSON.stringify(notification));
}
);
}
I also have capacitor.config.json like this:
"PushNotifications": {
"presentationOptions": ["badge", "sound", "alert"]
}
Also, I checked that my device and app have permission for notifications and are enabled both. I tried and test this issue with my app open and closed and open only in the background and the notification never arrives. What it could be? Any clue? Thank you
Android Phone Please Create the channel Like this, Test or Add screenshot for console Error
if (Capacitor.getPlatform() === 'android') {
PushNotifications.createChannel({
id: 'fcm_default_channel',
name: 'app name',
description: 'Show the notification if the app is open on your device',
importance: 5,
visibility: 1,
lights: true,
vibration: true,
});
}
I have installed FCM notification plugin and added following code in
FCM.onNotification().subscribe(data => {
if (data.wasTapped) {
this.route.navigateByUrl(`${data.routeUrl}`);
console.log("Received in background");
} else {
this.localNotifications.schedule({
title: data.title,
text: data.body,
foreground: true
})
this.localNotifications.on("click").subscribe((notification: any) => {
this.navCtrl.navigateForward([data.routeUrl]).then((entry) => {
}).catch((err) => {
console.log('Error while navCtrl:- ' + JSON.stringify(err));
});
})
console.log("Received in foreground");
};
});
With this I am able to navigate to a screen from the path provided in the body of notification when app is open but when app is in closed state or in background I'm unable to navigate to that screen
Please help me out regarding this issue
Regards
Versions
#react-native-firebase/app: 6.3.4
#react-native-firebase/messaging: 6.3.4
react: 16.9.0
react-native: 0.61.4
Inside my App.js file, I'm registering for notifications like this
...
import messaging from '#react-native-firebase/messaging';
const App: () => React$Node = () => {
const registerForNotifications = async () => {
const granted = await messaging().requestPermission();
if (granted) {
console.log('User granted messaging permissions!');
} else {
console.log('User declined messaging permissions :(');
}
await messaging().registerForRemoteNotifications();
const unsubscribe = messaging().onMessage(async remoteMessage => {
console.log('FCM Message Data:', remoteMessage.data);
});
const token = await messaging().getToken();
console.log({token});
return unsubscribe;
};
useEffect(() => {
SplashScreen.hide();
registerForNotifications();
}, []);
...
}
and it shows me that user granted messaging permissions, and it seems to register correctly for remote notifications, and finally I get the token, which seems to be ok and connected.
In firebase messaging console, I send a new notification and in possible targets it seems to be my user (Inside Cloud messaging menu)
So I do not see any error, but for some reason I sent multiple notifications, and I don't receive them, it doesn't matter if the app is open or close. I don't know what to do because I cannot see any error.
I am integrating push notification in react native with help of "react-native-push-notification" library. The push is coming from node js(backend).
I am successfully getting push in both environment Android and IOS.
Now i have two issues
1) In ios when i am getting push there is one parameter in notification payload "userInteraction". This parameter is for that user clicked the notification or not. Now it is working fine in android but in ios this is always false.
2)I want to set custom image in push notification, which is coming from push.
I am using "https://www.npmjs.com/package/react-native-push-notification" this library.
I have tried this code :-
export function setupPushNotification(handleNotification) {
PushNotification.configure({
onRegister: function (token) {
if (Platform.OS == 'ios') {
firebase.messaging().getToken().then((token) => {
alert(JSON.stringify(token))
requestaddAuthToke(token)
.then((data) => {
console.log("hello2 " + JSON.stringify(data))
})
.catch((error) => {
console.log("hello3 " + JSON.stringify(error.message));
})
});
}
else {
console.log("hello2 " + JSON.stringify(token.token))
requestaddAuthToke(token.token)
.then((data) => {
console.log("hello2 " + JSON.stringify(data))
})
.catch((error) => {
console.log("hello3 " + JSON.stringify(error.message));
})
}
},
onNotification: function (notification) {
const clicked = notification.userInteraction;
if (clicked)
handleNotification(notification.episodeCode)
if (Platform.OS == 'ios')
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
senderID: "529815244511",
permissions: {
alert: true,
badge: true,
sound: true
},
popInitialNotification: true,
requestPermissions: true,
})
return PushNotification
}
Any type of help will appreciated.
you are using react-native-push-notification and react-native-one-signal both at the same time. The only issue is onNotification not called when tapped on local notification in iOS only.
For a solution :
https://github.com/zo0r/react-native-push-notification/issues/919#issuecomment-439373380
I'm implementing Push Notifications on my Android Ionic 2 App with the Ionic Native FCM
When I'm receiving a notification in the foreground it works, but when I'm receiving a notification in the background and if I clicked on it, nothing happens.
app.component.ts
firebaseInit(){
//Firebase
this.fcm.subscribeToTopic('all');
this.fcm.getToken()
.then(token => {
console.log(token);
this.nativeStorage.setItem('fcm-token', token);
});
this.fcm.onNotification().subscribe(
data => {
console.log("NOTIF DATA: " + JSON.stringify(data));
if(data.wasTapped){
this.nav.push(MemoViewPage, {memo: {_id: data.memo_id}})
console.info('Received in bg')
}else{
let alert = this.alertCtrl.create({
title: data.subject,
message: "New memorandum",
buttons: [
{
text: 'Ignore',
role: 'cancel'
},
{
text: 'View',
handler: () => {
this.nav.push(MemoViewPage, {memo: {_id: data.memo_id}})
}
}
]
});
alert.present();
console.info('Received in fg')
}
});
this.fcm.onTokenRefresh()
.subscribe(token => {
console.log(token);
})
}
The if(data.wasTapped) condition doesn't go off once I clicked the notification from the system tray.
EDIT
The app opens but only in the Home Page not to the designated page that I set which is this.nav.push(MemoViewPage, {memo: {_id: data.memo_id}})
I also cannot receive notifications when the app is killed or not running.
you could use push plugin instead of FCM.
this.push.createChannel({
id: "testchannel1",
description: "My first test channel",
importance: 3
}).then(() => console.log('Channel created'));
and then you could use pushObjects to specify the needs for your notification like sound, ion etc.
const options: PushOptions = {
android: {},
ios: {
alert: 'true',
badge: true,
sound: 'false'
},
windows: {},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
}
};
After that it is easy for you to receive notifications whether you are using the app or not
const pushObject: PushObject = this.push.init(options);
pushObject.on('registration').subscribe((registration: any) => this.nativeStorage.setItem('fcm-token', token));
pushObject.on('notification').subscribe((notification: any) => console.log('Received a notification', notification));
you could use the option of forceShow:true in the pushObject init for the app to show the notification whether you are using the app or not.
And once you clicked the notification the notification payload is received by the app with the app home page set as default.