通知在前台非常有用,我同时获得console.log和导航操作。
在背景上显示它们,当我按打开它们时,我得到console.log和操作进行导航,但是这次我的通知主体未定义。我只能看到我从中设置的“数据” firebase控制台,而不是消息和标题。
关闭应用程序并按通知时,应用程序将打开,但没有console.log或导航至下一页操作。
import DetailPage from './Detail';
import { createStackNavigator } from 'react-navigation';
import firebase from 'react-native-firebase';
import { registerAppListener } from "./Listeners";
import firebaseClient from "./FirebaseClient";
class MainPage extends Component {
constructor(props) {
super(props);
this.state = {
token: ""
}
}
async componentDidMount() {
const channel = new firebase.notifications.Android.Channel(
'test',
'Channel Name',
firebase.notifications.Android.Importance.Max
).setDescription('A natural description of the channel');
firebase.notifications().android.createChannel(channel);
this.unsubscribeFromNotificationListener =
firebase.notifications().onNotification((notification) => {
const localNotification = new
firebase.notifications.Notification({
sound: 'default',
show_in_foreground: true,
})
.setNotificationId(notification.notificationId)
.setTitle(notification.title)
.setSubtitle(notification.subtitle)
.setBody(notification.body)
.setData(notification.data)
.android.setChannelId('test') // e.g. the id you chose above
.android.setSmallIcon('ic_stat_notification') // create this
icon in Android Studio
.android.setColor('#000000') // you can set a color here
.android.setPriority(firebase.notifications.Android.Priority.High);
firebase.notifications()
.displayNotification(localNotification)
.catch(err => console.error(err));
console.log(localNotification)
setTimeout(() => {
this.props.navigation.navigate('Detail')
}, 500)
registerAppListener(this.props.navigation);
firebase.notifications().getInitialNotification()
.then((notificationOpen: NotificationOpen) => {
if (notificationOpen) {
// Get information about the notification that was opened
const notif: Notification = notificationOpen.notification;
console.log('foo');
console.log(notif);
this.setState({
initNotif: notif.data
})
if (notif && notif.targetScreen === 'detail') {
setTimeout(() => {
this.props.navigation.navigate('Detail')
}, 500)
}
}
});
if (!await firebase.messaging().hasPermission()) {
try {
await firebase.messaging().requestPermission();
} catch (e) {
alert("Failed to grant permission")
}
}
firebase.messaging().getToken().then(token => {
console.log("TOKEN (getFCMToken)", token);
this.setState({ token: token || "" })
});
// topic example
firebase.messaging().subscribeToTopic('news');
//firebase.messaging().unsubscribeFromTopic('sometopic');
var offline = await AsyncStorage.getItem('headless')
if (offline) {
this.setState({
offlineNotif: offline
});
AsyncStorage.removeItem('headless');
}
}
componentWillUnmount() {
this.onTokenRefreshListener();
this.notificationOpenedListener();
this.messageListener();
this.unsubscribeFromNotificationListener();
this.registerAppListener();
}
showLocalNotification() {
let notification = new firebase.notifications.Notification();
notification = notification.setNotificationId(new
Date().valueOf().toString())
.setTitle("Test")
.setBody("Force touch to reply")
.setSound("bell.mp3")
.setData({
now: new Date().toISOString()
});
notification.ios.badge = 10
notification.android.setAutoCancel(true);
notification.android.setBigPicture("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png", "https://image.freepik.com/free-icon/small-boy-cartoon_318-38077.jpg", "content title", "summary text")
notification.android.setColor("red")
notification.android.setColorized(true)
notification.android.setOngoing(true)
notification.android.setPriority(firebase.notifications.Android.Priority.High)
notification.android.setSmallIcon("ic_launcher")
notification.android.setVibrate([300])
notification.android.addAction(new firebase.notifications.Android.Action("view", "ic_launcher", "VIEW"))
notification.android.addAction(new firebase.notifications.Android.Action("reply", "ic_launcher", "REPLY").addRemoteInput(new firebase.notifications.Android.RemoteInput("input")))
notification.android.setChannelId("test")
firebase.notifications().displayNotification(notification)
}
Listener.js
function displayNotificationFromCustomData(message: RemoteMessage){
if(message.data && message.data.title){
let notification = new firebase.notifications.Notification();
notification = notification
.setTitle(message.data.title)
.setBody(message.data.body)
.setData(message.data)
.setSound("bell.mp3")
notification.android
.setPriority(firebase.notifications.Android.Priority.High)
notification.android.setChannelId("test")
firebase.notifications().displayNotification(notification);
console.log(notification);
console.log('received');
}
}
export async function registerHeadlessListener(message: RemoteMessage){
await AsyncStorage.setItem('headless', new Date().toISOString());
displayNotificationFromCustomData(message);
}
// these callback will be triggered only when app is foreground or
background
export function registerAppListener(navigation){
this.notificationListener =
firebase.notifications().onNotification(notification => {
firebase.notifications().displayNotification(notification);
})
this.notificationOpenedListener =
firebase.notifications().onNotificationOpened((notificationOpen:
NotificationOpen) => {
const notif: Notification = notificationOpen.notification;
console.log(notif);
console.log('works');
// if(notif.data.targetScreen === 'detail'){
setTimeout(()=>{
navigation.navigate('Detail')
}, 500)
//}
// setTimeout(()=>{
// alert(`User tapped notification\n${notif.notificationId}`)
// }, 500)
});
this.onTokenRefreshListener = firebase.messaging().onTokenRefresh(token => {
console.log("TOKEN (refreshUnsubscribe)", token);
});
this.messageListener = firebase.messaging().onMessage((message:
RemoteMessage)
=> {
displayNotificationFromCustomData(message);
});
}
和我的AndroidManifest:
<service android:name="io.invertase
.firebase.messaging.RNFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:host="example.com" android:scheme="http"/>
<data android:host="example.com" android:scheme="https"/>
</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" />