I am trying to implement the notification which working fine only facing one issue that when I want to show icon only with data it will show as an image.
The Library I am using is react-native-push-notification
For example, I want to show like this but it shows large image too on click of an arrow button.
Right now it is like this
That is how I want.
Here is my AndroidManifest.xml
<!-- Change the resource name to your App's accent color - or any other color you want -->
<meta-data android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#mipmap/ic_notification"/>
<meta-data android:name="com.dieam.reactnativepushnotification.notification_color"
android:resource="#android:color/white"/>
While on server side
$notification = array('content-available' => true, 'mutable-content' => true, 'title' => $title, 'text' => $body, 'icon' => $icon, 'sound' => 'default', 'badge' => '1');
If I pass icon then nothing will show if I use image then icon show but with the big image too.
My code is as below
import PushNotification from "react-native-push-notification";
import { PushNotificationIOS } from "react-native";
import { NavigationActions, StackActions } from "react-navigation";
import {ToastAndroid} from 'react-native';
const localNotification = data => {
console.log("const localNotification" + JSON.stringify(data));
if (data) PushNotification.localNotification(data);
return null;
};
let getToken;
const setToken = token => (getToken = token.token);
const configure = () => {
PushNotification.configure({
onRegister: setToken,
// largeIcon: "https://stag2.com/uploads/qr/407xg1.png",
// smallIcon: "ic_notification",
// ongoing: true,
onNotification(notification) {
onNotification(notification);
},
senderID: "5545454654654654",
// SmallIcon:"ic_notification",
permissions: {
alert: true,
badge: true,
sound: true
},
popInitialNotification: true,
requestPermissions: true
});
};
let onNotification = (notification) => {
notification.android.setSmallIcon('ic_notification')
// if (!!notification.title && !!notification.body) {
// PushNotification.localNotification({
// title: notification.title,
// message:"urfusion",
// });
// }
};
export { configure, localNotification, getToken };
I got what I wanted if I push local notification which called when the app opens on notification click event but I want on remote push notification not on local one.
let onNotification = (notification) => {
notification.android.setSmallIcon('ic_notification')
// if (!!notification.title && !!notification.body) {
PushNotification.localNotification({
title: notification.title,
message:"urfusion",
});
}
};
Icons need to be with a transparent background. you can read more here :
read more
On the other hand, for notification, you need to use different icons for different versions of android. you can read more here :
read more
Related
I am having an issue where the local notification is not displaying in android though it is displaying in IOS. I have created permissions and battery optimization check to see if that is the problem. The notification does make a sound and appear shows a little square in the upper left that if I click and drag does show the local notification. I am using an emulator right now and I have tried it on a real device.
This is the way I am calling the notification.
<Button
title="Trigger Push Notification"
size="large"
onPress={() => onDisplayNotification('default', 'Default Channel', 'Spotback
Android', 'Local push notification')}
/>
This is is the Notifee component.
import notifee, { AndroidStyle, AuthorizationStatus, Notification } from '#notifee/react-native';
import { Alert } from 'react-native';
export const onDisplayNotification = async (id, name, title, body, smallIcon?) => {
// Request permissions (required for iOS)
await notifee.requestPermission();
const settings = await notifee.getNotificationSettings();
const batteryOptimizationEnabled = await notifee.isBatteryOptimizationEnabled();
if (batteryOptimizationEnabled) {
// 2. ask your users to disable the feature
Alert.alert(
'Restrictions Detected',
'To ensure notifications are delivered, please disable battery optimization for the app.',
[
// 3. launch intent to navigate the user to the appropriate screen
{
text: 'OK, open settings',
onPress: async () => await notifee.openBatteryOptimizationSettings(),
},
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
],
{ cancelable: false }
);
}
if (settings.authorizationStatus == AuthorizationStatus.AUTHORIZED) {
console.log('Notification permissions has been authorized');
} else if (settings.authorizationStatus == AuthorizationStatus.DENIED) {
console.log('Notification permissions has been denied');
}
// }
// Create a channel (required for Android)
const channelId = await notifee.createChannel({
id,
name,
});
await notifee.displayNotification({
title,
body,
android: {
channelId,
smallIcon,
pressAction: {
id,
},
},
});
};
Please change your channel id (default) and channel name (Default Channel) to something else like:
id: custom_channel
name: custom_channel
I am implementing a react-native app that receives firebase push notification. When a notification arrives the app navigate to a screen to show the notification.
I followed this approach using reference:
"Navigating without the navigation prop"
https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
When I tested this with debug mode, it works perfectly. But when I tested in release mode (android signed app) it does not work.
Especially, when the notification arrives when the app is open, it does not work. There is no error message and the app become freezing and in a 30 seconds or so, the app crashes.
Here are package info:
"react": "16.8.3",
"react-i18next": "10.12.2",
"react-native": "0.59.10",
"react-native-firebase": "5.5.6",
"react-native-gesture-handler": "1.3.0",
"react-navigation": "3.11.1",
Basically, I tried this
"Navigating without the navigation prop"
https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
Similarly, this one too:
https://github.com/react-navigation/react-navigation/issues/742
I am using not class component but functional component.
// Navigator.js
const switchNavigator = createSwitchNavigator({
ResolveAuth: ResolveAuthScreen,
loginFlow: createStackNavigator({
Signin: SigninScreen,
Signup: SignupScreen
}),
helpFlow: createStackNavigator({
Help: HelpScreen,
}, {headerLayoutPreset: 'center'}),
mainFlow: createBottomTabNavigator({
Ask: createStackNavigator({
AskMain: AskScreen,
AskWait: AskWaitScreen,
}, {headerLayoutPreset: 'center'}),
Chat: createStackNavigator({
ChatList: ChatListScreen,
Chatting: ChatScreen,
}, {headerLayoutPreset: 'center'}),
Profile: createStackNavigator({
Account: AccountScreen,
AccountEdit: AccountEditScreen,
ProfileContract: ProfileScreen
}
, {headerLayoutPreset: 'center'})
},
...
export default createAppContainer(switchNavigator);
// App.js
import Navigator from './Navigator';
import { useTranslation } from 'react-i18next';
import { navigate, setNavigator } from './src/navigationRef';
const App = Navigator;
export default () => {
// setup language
const { t } = useTranslation();
// use effect
useEffect(() => {
// notification listener (triggered when a particular notification has been received)
// if the app is foreground, we need to navigate the screen
const listenerFG = firebase.notifications().onNotification((notification: Notification) => {
console.log('onNotification', notification);
Alert.alert(
t('AppScreen.title'),
t('AppScreen.message'),
[
{text: t('yes'), onPress: () => navigate('Help', { notificationBody: notification })},
],
{cancelable: true},
);
});
listenerForAppClosed();
return () => {
listenerFG();
}
}, []);
return (
<App ref={(navigator) => { setNavigator(navigator) }} />
);
// navigationRef.js
import { NavigationActions } from 'react-navigation';
let navigator;
// nav is coming from react navigation
export const setNavigator = navRef => {
console.log('navigation ref', navRef);
// set navigator
navigator = navRef;
};
export const navigate = (routeName, params) => {
console.log('[navigate dispatch] navigator', navigator);
navigator.dispatch(
NavigationActions.navigate({
routeName,
params
})
);
};
In debug mode, using `navigate('any screen') works like a charm, but in release mode, it does not work.
But one strange thing is that the following navigation works. A user opens a push notification when the app is not foreground state.
// part of App.js
// listen the notification being opened or clicked when the app is closed
const listenerForAppClosed = async() => {
// app closed
const notificationOpen: NotificationOpen = await firebase.notifications().getInitialNotification();
if (notificationOpen) {
// app was opened by a notification
console.log('getInitialNotification', notificationOpen);
// get information about the notification that was opened
const notification: Notification = notificationOpen.notification;
//// ignore the same notification id since the same notification is received again, don't know why.
// get noti id from storage
const notiId = await AsyncStorage.getItem('notiId');
// set noti id to storage
await AsyncStorage.setItem('notiId', notification.notificationId);
if (notification.notificationId === notiId) {
console.log('notification id is the same');
} else {
console.log('navigating to helpscreen...');
// navigate to Help screen
navigate('Help', { notificationBody: notification });
}
}
}
The problem happens both on Android emulator and a device (Android9).
Why the navigate('Help') does not work in release mode? I searched many documents and I feel that it should work in release mode too.
Is there any other way to navigate to a screen from top-level (like App.js)?
I found the source of the problem.
I tested several things.
I wanted to know that whether very simple app in release mode navigates properly.
So, I just followed this posting:
https://medium.com/#katharinep/firebase-notification-integration-in-react-native-0-60-3a8d6c8d56ff
Here are what I did:
- created two screens: Home and Notification.
- Re-created the app with latest react-native#0.60.6 and react-navigation#4.0.9
- sent cloud message not from the app but from the firebase cloud messaging
It worked! When a notificaiton arrives the app navigated to the notification screen.
So I tried to track down the source of the problem.
- tried to add more screens
- added more providers and context
- sent message from the app
Finally, I found the source. It was how I used 'navigateRef.js'
Originally I used it like this:
// App.js
import { navigate, setNavigator } from './src/navigationRef';
<App ref={(navigator) => { setNavigator(navigator) }} />
// navigationRef.js
import { NavigationActions } from 'react-navigation';
let navigator;
// nav is coming from react navigation
export const setNavigator = navRef => {
console.log('navigation ref', navRef);
// set navigator
navigator = navRef;
};
export const navigate = (routeName, params) => {
console.log('[navigate dispatch] navigator', navigator);
navigator.dispatch(
NavigationActions.navigate({
routeName,
params
})
);
};
I simply used the exact the code from react-navigation:
https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
// App.js
import NavigationService from './src/NavigationService';
<App
ref={navigationRef =>
{NavigationService.setTopLevelNavigator(navigationRef);}}
/>
// NavigationService.js
import { NavigationActions } from 'react-navigation';
let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}
function navigate(routeName, params) {
_navigator.dispatch(
NavigationActions.navigate({
routeName,
params,
})
);
}
// add other navigation functions that you need and export them
export default {
navigate,
setTopLevelNavigator,
}
Then I worked! I do not know the difference of these two codes.
The first one worked perfectly in debug mode but not in release mode, especially the app is in foreground.
Could anyone tell me the difference? Why the first code does not work?
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.
I am trying to get this working https://ionicframework.com/docs/native/push/
With FireBase Cloud Messaging
Here is the code
import { Push, PushObject, PushOptions, AndroidPushOptions, IOSPushOptions } from '#ionic-native/push';
pushsetup() {
const options: PushOptions = {
android: {
senderID: '**********',
icon: "notification",
iconColor: "blue",
sound: true,
vibrate: true,
forceShow: true
},
ios: {
alert: true,
badge: true,
sound: true
},
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => {
if (notification.additionalData.foreground) {
let youralert = this.alertCtrl.create({
title: 'New Push notification',
message: notification.message
});
youralert.present();
}
});
pushObject.on('registration').subscribe((registration: any) => {
//do whatever you want with the registration ID
});
pushObject.on('error').subscribe(error => alert('Error with Push plugin' + error));
}
How push looks now:
Unfortunately there is still no custom icon or sound or vibration :(
I copied the notification png, basically everywhere now in the android/res folder :)
Has anyone had any success with this? Do you actually have to use the AndroidPushOptions import anywhere?