问题
I am using zo0r react-native-push-notification library.
"react": "16.0.0-alpha.12",
"react-native": "^0.45.1",
"react-native-push-notification": "^3.0.0"
This code runs every time I open an app:
PushNotification.configure({
onNotification: function(notification) {
console.log('onNotification');
ToastAndroid.show('onNotification', 3000);
}
});
I send local push notification from background service:
PushNotification.localNotification({
message: 'Hello World',
smallIcon: 'ic_launcher'
});
The notification gets delivered. When I click it, onNotification
method doesn't get called, then when I receive another notification, it actually gets called. It seems like it works only if app is in memory atm.
Am I doing something wrong?
I have opened a GitHub issue as well.
回答1:
In my code I configured notifications outside App
class - that was an issue. I just moved the configuration to App constructor and now it works just fine, onNotification gets called with no problem:
class App extends React.Component {
constructor(props) {
super(props);
PushNotification.configure({ ... });
}
}
回答2:
It's specifically written to not put the configuration in the React life-cycle. Otherwise Android won't have the right behavior (I had so mush pain with this point !). Here you have a nice tutorial: https://product.farewell.io/visible-react-native-push-notifications-that-work-on-both-ios-and-android-5e90badb4a0f It's bad explained, but the approach is perfect. Use a class to initialize and call the methods. Initialize the class in the top component as he suggests. It works good. Complete the missing informations with this tutorial: https://shift.infinite.red/react-native-node-js-and-push-notifications-e851b279a0cd Good luck !
回答3:
In my case,I followed everything as per the document including React life cycle thing for android except below change where I was not configuring proper intent filter action i.e.
<action android:name="com.google.firebase.MESSAGING_EVENT" />
Make below change and this should work
<service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService" android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Previously I was using this action because of that listener was not triggering
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
来源:https://stackoverflow.com/questions/45616252/react-native-push-notification-onnotification-doesnt-trigger