I'm trying to get The data from the Notification when the App is Killed or in background here is what I've did :
php side :
$msg = array
(
'body' => $msg,
'title' => $title,
'click_action' => "OPEN_ACTIVITY_1"
);
$fields = array
(
'to' => $token,
'notification' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
in my luncher Activity :
if(getIntent().getExtras()!=null){
Strig msg = getIntent().getExtras().getString("body");
String title =getIntent().getExtras().getString("title");
Log.i(TAG,"Message "+msg);
Log.i(TAG,"Title " +title);
}
it's Returning null for both msg and title ..
here is the code for onMessageReceived()
public void onMessageReceived(RemoteMessage remoteMessage) {
clickAction= remoteMessage.getNotification().getClickAction();
NotificationHelper h = new NotificationHelper(this);
Map<String,String >data = remoteMessage.getData();
title=data.get("title");
msg=data.get("body");
Log.i(TAG, "onMessageReceived: "+clickAction);
h.createNotificationWithId(msg,title,clickAction);
}
The issue you are facing has to do with the structure of the JSON payload.
See this question here for more examples.
The upshot is that if you have the 'notification' key and object value, you will not be able to handle the onMessageReceived in the background.
//Will not work in your situation
{
"notification":{
"title": "hello",
"body": "this is body"
},
"to": "c5iuJ7iDnoc:APA91bG6j2c5tiQ3rVR9tBdrCTfDQYxkPwLuNFWzRuGHrBpWiOajR-DKef9EZEEVKA-kUBfXVcqHT-mClYfad06R_rBjhRZFKVdBL7_joXE5hFEwR45Qk8wgQdia2b-LmjI1IheFGZS8"
}
While this one will work because notification is absent, but the 'data' key is present.
//This will work for your situation
{
"data":{
"title": "hello",
"body": "this is body"
},
"to": "c5iuJ7iDnoc:APA91bG6j2c5tiQ3rVR9tBdrCTfDQYxkPwLuNFWzRuGHrBpWiOajR-DKef9EZEEVKA-kUBfXVcqHT-mClYfad06R_rBjhRZFKVdBL7_joXE5hFEwR45Qk8wgQdia2b-LmjI1IheFGZS8"
}
One other thing, if you have both the 'notification' and 'data' keys, it will default to the first example and you will not be able to manually handle it in the onMessageReceived
Related
I have data notification and on some devices i always receive it,on some only when app is running and on one device i never receive it.
I set priority to high but nothing changes im not sure is it written proper, here is php code
$naslovPoruke = "Пробна апликација";
$path_to_fcm = "https://fcm.googleapis.com/fcm/send";
$server_key =my_key_here";
$key = "/topics/sve";
$msg = array
(
'title' => $naslovPoruke,
'body' => $poruka,
'idObjave' => $idObjave,
'naslovObjave' => $naslovObjave,
'tekstObjave' => $tekstObjave,
);
$headers = array
(
'Authorization:key=' .$server_key,
'Content-Type:application/json'
);
//$fields = array
//(
// 'to' => $key,
// 'notification' => array('title'=>$naslovPoruke,'body'=>$poruka),
// 'data' => $msg
//);
$fields = array
(
'to' => $key,
'data' => $msg,
'priority'=>"high",
'ttl'=>"0"
);
$payload = json_encode($fields);
echo $payload;
$curl_session = curl_init();
curl_setopt($curl_session,CURLOPT_URL,$path_to_fcm);
curl_setopt($curl_session,CURLOPT_POST,true);
curl_setopt($curl_session,CURLOPT_HTTPHEADER,$headers);
curl_setopt($curl_session,CURLOPT_RETURNTRANSFER,$headers);
curl_setopt($curl_session,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl_session,CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V4);
curl_setopt($curl_session,CURLOPT_POSTFIELDS,$payload);
$result = curl_exec($curl_session);
echo $result;
curl_close($curl_session);
?>
Also this is json response:
{
"to": "\/topics\/sve",
"data": {
"title": "pushuptitle",
"body": "pushupbody",
"idObjave": "linktoimage.jpg",
"naslovObjave": "apptitle",
"tekstObjave": "appbody"
},
"priority": "high",
"ttl": "0"}
{
"message_id": 6358638519123612486
}
Im not sure why i dont receive this message on all devices?
You can first check if you have notifications enabled on the device that doesn't get the notification.
Please consider the following issue:
I am using the following plugin for Xamarin to perform push notifications, I am attempting to get this running on both iOS and Androids.
https://github.com/CrossGeeks/FirebasePushNotificationPlugin
I am also using the following PHP code to send push notifications to the device from a website.
$fields = array
(
'to' => $ID->notification_token,
"content_available" => true,
'priority'=>10,
'notification' => array('title' => 'You have a new message', 'body' => 'Hooray', 'sound'=>'default', 'vibration'=>'default'),
);
$headers = array
(
'Authorization: key=' . PUSH_NOTIFICATION_API_ACCESS_KEY,
'Content-Type: application/json',
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
Now the issue is on iOS I find that the push notification is reliable and runs perfectly when the app is in the foreground, but as soon as I background it (or lock the screen), they stop coming through until I foreground it again, then all of the notifications sent while it was in the background all come through at once.
I have enabled background processes in my info.plist as according to the plugins "Getting Started" guide.
I have tried changing content_availiable to content-availiable, also moving it into the notification array, also setting the value of it to true, 'true', 1 and '1'
I have also tried adding "alert" => "" to both the notification and the overall payload, however I still can't get it to work, outside of the foreground unlocked state.
I also notice that nothing appears to be triggering in the actual notification list (Pulled down from top of screen), the only way I know that the notifications are being received is from playing a certain sound file as it comes through and writing in the debug log.
Any assistance will be appreciated, thanks for your time.
Make sure your message Json has the {"content-available" : "1", "alert" : ""} attributes if you want it to show up on iOS when not running in background.
As for Android, push notifications really are not 100% realiable, there are device specific impediments that may block your notification from showing up.
There might be a "test send" feature on Firebase (I've only used Azure Push Hub so far) so you can try and see if your message Json is configured correctly.
I would try sending a Data Message instead
$fields = array
(
'to' => $ID->notification_token,
"content_available" => true,
'priority'=>10,
'data' => array('title' => 'You have a new message', 'body' => 'Hooray', 'sound'=>'default', 'vibration'=>'default'),
);
Use ApnsConfig to show alerts in iOS when the app is in background. This worked for me.
var pushMessage = new FcmMessage
{
Data = new Dictionary<string, string>
{
{ Constants.PushMessages.MessageId, $"{message.MessageId}" },
{ Constants.PushMessages.TopicId, $"{message.TopicId}" },
{ Constants.PushMessages.Type, $"{message.Type}" },
{ Constants.PushMessages.Title, message.Title },
{ Constants.PushMessages.Content, message.Content },
{ Constants.PushMessages.CreatedBy, message.CreatedBy },
{ Constants.PushMessages.CreatedOn, $"{message.CreatedOn}" }
},
Token = registrationToken,
Apns = new ApnsConfig
{
Aps = new Aps
{
Alert = new ApsAlert
{
Title = message.Title,
Body = message.Content
}
}
}
};
await FirebaseMessaging.DefaultInstance.SendAsync(pushMessage);
I know this question has been asked and answered many times but none of the solution is working for me.
I have followed ionic.io documentation https://docs.ionic.io/services/push/ to implement push notification and it works fine when app is in foreground. I am also able to receive notification when app is closed. Now when user clicks on that notification, I want to open a specific view.
As per documentation, To handle push notifications in your app, we need to listen to the cloud:push:notification event using angular’s $on.
$scope.$on('cloud:push:notification', function(event, data) {
var msg = data.message;
alert(msg.title + ': ' + msg.text);
});
This code is working fine when app is foreground. But when app is closed and user opens the app by tapping the push notification, I want to open specific view/controller.
I have placed the above code in .run function and outside $ionicPlatform.ready function.
Here is my code to call FCM Rest service
function sendFCMNotification($request_data){
$ch = curl_init("https://fcm.googleapis.com/fcm/send");
//The device token.
$token = $request_data['device_id'];
//Title of the Notification.
$title = $request_data['title'];
//Body of the Notification.
$body = $request_data['body'];
//Creating the notification array.
$notification = array('title' =>$title , 'body' => $body,'content-available'=> '1');
//This array contains, the token and the notification. The 'to' attribute stores the token.
$arrayToSend = array('to' => $token, 'notification' => $notification);
//Generating JSON encoded string form the above array.
$json = json_encode($arrayToSend);
//Setup headers:
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key= {MY GCM KEY}';
//Setup curl, add headers and post parameters.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
curl_exec($ch);
//Close request
curl_close($ch);
}
Can anyone help me in achieving this?
Pushwoosh provides a method which can tell us if the app has been launched by clicking push notification or not.
https://rawgit.com/Pushwoosh/pushwoosh-phonegap-3.0-plugin/master/Documentation/files/PushNotification-js.html#PushNotification.getLaunchNotification
Is there any similar function in ionic push plugin?
If you are sending a CURL req to ionic for push use this data structure
$notficationHolder =array(
"user_ids" => array(),
"profile" => "push",
"notification"=>array(
"android"=>array(
"title"=>'TITLE',
"message"=>"You have a notification",
"sound" => "sound",
"icon_color" => "#FA2B2E",
"icon" => "notification",
/* "image" => "https://pbs.twimg.com/profile_images/617058765167329280/9BkeDJlV.png", */
"payload" => array(
'$state'=> 'main.myProfile',
'$stateParams'=> array()
)
),
"ios"=>array(
"sound" => "default",
"payload" => array(
'$state'=> 'main.myProfile',
'$stateParams'=> array()
)
)
)
);
This is an array. json encode it and curl it to ionic. The catch is your payload property in the notification object.
you need to add in payload attribute
{"$state":'yourStateName','$stateParams':{'paramOne':1,'paramTwo':2}}
I am developing mobile app using ionic framework.I have Successfully implemented push notification.When I click on the notification I want it should go on particular page.How will I do this?
In Client Side:
var user = $ionicUser.get();
if(!user.user_id) {
// Set your user_id here, or generate a random one.
user.user_id = $ionicUser.generateGUID();
};
// Identify your user with the Ionic User Service
$ionicUser.identify(user).then(function(){
//$scope.identified = true;
//alert('User ID ' + user.user_id);
//alert("here");
$ionicPush.register({
canShowAlert: true, //Can pushes show an alert on your screen?
canSetBadge: true, //Can pushes update app icon badges?
canPlaySound: true, //Can notifications play a sound?
canRunActionsOnWake: true, //Can run actions outside the app,
onNotification: function(notification) {
// Handle new push notifications here
// console.log(notification);
return true;
}
});
});
});
})
.config(['$ionicAppProvider', function($ionicAppProvider) {
$ionicAppProvider.identify({
app_id: 'xxxxxxxxxxxxx',
api_key: 'xxxxxxxxxxxxxx',
dev_push: false
});
}])
In Server Side I have used php:
$deviceToken = 'APA91bHKwBKrIjmmZ9lke97fl_GbOQ9iRRo-S2sNnZp085hPqVaTHMOd0wqhYFF1PtrtOzFrETX7ZNIkU0JDhC49Tby_AEFIQFRX99B0QpZd7xdiTqsP6sZ08P-8ESdJAie5AJNxhW89nQ7S9evZNcAc9tsJaG91Xw';
$registrationIds = explode(",",$deviceToken);
//$registrationIds = array($deviceToken);
// prep the bundle
$msg = array
(
'notId' => time(),
'message' => 'Technovault is awesome!!!',
'title' => 'Title',
'smallIcon' =>'icon'
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . 'xxxxxxxxxx',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
}
else {
echo "Error";
}
notification you receive on client side has parameter foreground associated. It's value will be false when you come to application from clicking notification. So this is how you can perform specific action:
onNotification: function(notification) {
if(notification.foreground == false){
//add your logic here to navigate to other page
}
}
I resolve a similar situation some days ago. I've an app with articles list and article details. When there is a new article the server send a notification than include the article id in the playload.
When the app receive the notification, i save it in the localStorage and when the user click on the notification, with the resume event i can read this localStorage item and change the state of the app and show the article controller view for this article id.
I haven't used the ionPush library, i used the Cordova PushPlugin because i have a custom push notification server.
When the app received the notification:
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
if (ionic.Platform.isAndroid() && notification.event == 'message') {
var newsid=notification.payload.newsid;
if (typeof newsid != 'undefined') {
// save the newsid to read it later in the resume event
$window.localStorage.setItem('goafterpush',newsid);
}
}
});
And the resume event:
$ionicPlatform.on("resume",function(event){
// read the newsid saved previously when received the notification
var goafterpush=$window.localStorage.getItem('goafterpush');
if (goafterpush) {
$window.localStorage.removeItem('goafterpush');
$state.go('app.newsdetail',{id:goafterpush});
}
});
I hope this code can help you.
I've this working for Android and iOS, in python I've set payload with the state name and Id parameter
payload = {"$state":"state.name", "$stateParams": "{\"id\": \""+time()+"\"}"}
Then I include it with all the other message stuff
"payload": payload
This should happen inside your $msg array, and that's it, when the user clicks the notification your app opens and goes to the defined state using the provided parameter.
Now the pushwoosh works without problem. I can see the notification on the upper left corner of the Android phone. How can I set the notification to be pop-up onto screen rather than the notification on upper left only, even the phone is in silence mode!
Which way should I go for the customization? Thx
function pwCall( $action, $data = array() ) {
$url = 'https://cp.pushwoosh.com/json/1.3/' . $action;
$json = json_encode( array( 'request' => $data ) );
$res = doPostRequest( $url, $json, 'Content-Type: application/json' );
print_r( #json_decode( $res, true ) ); }
pwCall( 'createMessage', array( '
application' => PW_APPLICATION,
'auth' => PW_AUTH,
'notifications' => array(
array(
'send_date' => 'now',
'content' => 'test',
'ios_badges' => 3,
'data' => array( 'custom' => 'json data' ),
'link' => 'http://pushwoosh.com/'
)
)
)
);
To configure how to display the incoming push notification, you should write your own logic in the receiver in Android app, as specified in this page.
Currently, the tutorial currently uses the following the show the message:
private void showMessage(String message)
{
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
Try to create your own logic (user interface, popup method & timing, etc) in the function.