Push notification with GCM and corresponding Chat Activity - android

I have implemented GCM in my application and I have tested via two android devices and it works. I am implementing a simple chat application within my app. My app is actually selling or buying products.
When a user wants to give a bid, then he types his message and send it to server and gcm is activated and seller receives the potential customer's message. When seller clicks on the received push notification message, it should take him to the chat activity. With this simple text message, how do I know which corresponding product?

What I've mentioned in the comments, if you are sending via a server you can do this:
$registatoin_ids = array($regId);
$message = array("message" => $message, "productId" => $uniqueProductId);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
then in your intent service:
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
String message = extras.getString("message");
String productId = extras.getString("productId");
When you go to build your notification:
Intent productWindow = new Intent(this, ProductActivity.class);
productWindow.putExtra("productId", productId);
PendingIntent contentIntent = PendingIntent.getActivity(this,0,productWindow , 0);

You could format your GCM messages in a specific way, so the message overhead is sent with a format that you know and then you can parse it and take any needed actions. For example, you could send your messages this way:
ProdID:123456,Action:Bid,...
You would take the comma (or any other sign) as separator, get the parts of it and do whatever you want with them.

Related

My android app can't receive fcm message from python

I'm building android app with firebase cloud messaging.
My app can receive message from FCM console.
However, it cannot receive from python, although the response is good.
Could you give me some advice?
class fbMessaging():
def __init__(self):
cred = credentials.Certificate('./env/firebase.json')
firebase_admin.initialize_app(cred)
def send_to_device(self, text, token):
message = messaging.Message(
data = {
'title': 'test',
'body': text,
},
token = token,
)
response = messaging.send(message)
return response
def main():
fm = fbMessaging()
res = fm.send_to_device('test', 'MY CORRECT TOKEN')
print(res)
onMessageRecieved is here
override fun onMessageReceived(message: RemoteMessage?) {
val from = message!!.from
val data = message.data
Log.d(TAG, "from:" + from!!)
Log.d(TAG, "data:$data")
}
Printed response is below.
projects/match-XXXXX/messages/0:1554291593xxxxxx%43f99108f9xxxxxx
Using Firebase Cloud Messaging, you can send Notification payload or Data payload or both.
Notification Payload contains
title - Notification Title
body - Notification body
The key names fixed and can't be changed.
Data Payload, on the other hand, is simply a key-value pair and you can send any key name with string type as its value.
FCM Behavior:
Based on whether the app is in the foreground or background and the existence of Notification payload or Data payload or both, the FCM message is received by different components in the app.
Handling of FCM notification as per documentation,
Notification messages delivered when your app is in the background. In this case, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default.
Messages with both notification and data payload, when received in the background. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
This behavior has been explained clearly in the Receive Messages Section.
As you can see, if only in the case where Notification payload is sent in standalone you don't have to build Notification UI. Otherwise, you have create the Notification UI when onMessageReceived is called.
Using Python:
Notification Payload Example:
message = messaging.Message(
notification=messaging.Notification(
title='This is a Notification Title',
body='This is a Notification Body',
),
token=registration_token,
)
Data Payload Example:
message = messaging.Message(
data={
'score': '850',
'time': '2:45',
},
token=registration_token,
Both:
message = messaging.Message(
notification=messaging.Notification(
title='This is a Notification Title',
body='This is a Notification Body',
),
data={
'score': '850',
'time': '2:45',
},
token=registration_token,

Handle Firebase topics notification on Android

I'm trying to send push notifications throught FCM services.
In my MainActivity I write this code:
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
// gcm successfully registered
// now subscribe to `global` topic to receive app wide notifications
FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL);
displayFirebaseRegId();
} else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
// new push notification is received
String message = intent.getStringExtra("message");
Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
}
}
};
In order to subscribe user to a topic.
From backend I make a call to FCM service at this link : https://fcm.googleapis.com/fcm/send
in which I pass this JSON:
{
"to":"/topics/global",
"data":{
"title":"test",
"is_background":false,
"message":"testmessage",
"image":"",
"payload":{
"team":"Test",
"score":"5.6"
},
"timestamp":"2017-05-23 11:55:35"
}
}
and I get this response:
{\"message_id\":8863205901902209389}
But my device doesn't show any notifaction, exept if I use Firebase console with "user segment" or "single device" . Also in Firebase console doesn't works "topic" way.
Thank you in advance for any response.
There are two types of FCM messages.
Notification Messages
Data Messages
On the client side, Notification messages are handled by FCM and automatically displayed in the notification window. If you are using Data Messages, your app needs to handle the received message and create a notification.
The sample payload in your question is a data message and hence it is not displayed in notification (I assume you didn't do any handling). The notifications sent via FCM console are always notification messages and hence those are automatically displayed.
Refer to this FCM page for more details on this.

FCM console push works but server push does not

GCM was working fine but now fcm do not recive any notification if it was sent by server it only work if o send from firebase console I am almost sure the problem is in array form i have in app:
String messageBody = remoteMessage.getNotification().getBody();
and in php:
$fields = array(
'registration_ids' => $this->devices,
'data' => array( "message" => $message ),
);
what do you think please
In your question you are sending a data-message, which is a message with a payload like:
{"registration_ids" : ["token1"], "data" : { "key1" : "value1"}}
To receive the data payload (in the example: key1:value1), the client app should to use:
String value1 = remoteMessage.getData().get("key1");
FCM also supports display-messages.
Example:
{"registration_ids" : ["token1"], "notification" : { "body" : "hello"}}
These messages are automatically displayed when the app is in background.
And they call onMessageReceived() only if the app is already open and in foreground.
In this second case you can access the field of the original notification via: remoteMessage.getNotification().getBody()
Display messages can also include a {"data" : { "key1" : "value1"}}.
If the app is in foreground it can access these values like a data-message.
If the app in bakground you need to wait until the user click the notification and starts an activity.
At that point you can access the data via: getIntent().getExtras()
PS: the notifications sent via Firebase Web Console are only display-messages.

Message notifications and pull content

I know that this may possible be a duplicate question, but the other questions don't answer mine.
I am working on an app that pulls notifications (specifically notifications for new WhatsApp messages) from the status bar and reads their content. I have managed to pull the notification title and the message content.
The problem is, when more than one unread message is received, the notification switches from using EXTRA_TEXT to EXTRA_SUMMARY_TEXT (then returning e.g. "2 new messages" instead.
It must possible to separate the messages somehow, seeing as certain existing apps do it (e.g. Snowball combines all messages and displays them in one place, showing message content even when multiple messages have been received and are still unread).
I know that users can send messages via Intents. However, I cannot seem to access incoming intents and have, therefore, assumed that WhatsApp uses explicit intents to send messages.
Intent i = new Intent("com.test.testapp.NOTIFICATION_LISTENER");
Bundle extras = sbn.getNotification().extras;
if(sbn.getPackageName().contains("com.whatsapp"))
{
String title = extras.getString(Notification.EXTRA_TITLE);
String summary = extras.getString(Notification.EXTRA_SUMMARY_TEXT);
String msg = extras.getString(Notification.EXTRA_TEXT);
if(msg != null)
{
i.putExtra("notification_event", msg);
}
else
{
i.putExtra("notification_event", summary);
}
}
else
{
i.putExtra("notification_event","...");
}
sendBroadcast(i);
My question:
How can I display all received messages without getting "2 new messages" as content OR is there a better way of doing this?
I need to access message content, the sender's number and the time that the message was received, so that I can save it to a database.
Any help would be appreciated.
WhatsApp application has structure for sending notification like this :
Case Notification
Message comes from A : Hi Title : A Text: Hi
Message comes from A : How are you Title : A Text: How are you
Title : A Text: 2 new messages
Message comes from B : Hello Title : B Text: Hello
Title : B Text: 1 new message
Title : A Text: 2 new messages
Title : WhatsApp Text: 3 new messages from 2 conversation
---- Here comes the stacking ----
Message comes from C : Good work Title : C Text: Good work
Title : C Text: 1 new message
Title : B Text: 1 new message
Title : A Text: 2 new messages
Title : WhatsApp Text: 4 new messages from 3 conversation
---- This way when new sender message comes, previoud notifications also comes and we get callback in NotificationListener ----
Last notification comes with Title as Package Name : WhatsApp and Text as : X messages from Y Conversation
To get Text :
sbn.getNotification().extras.getCharSequence(Notification.EXTRA_TEXT).toString();
To get Title :
sbn.getNotification().extras.getCharSequence(Notification.EXTRA_TITLE).toString();
To work with this sturcture of stacking, we need to parse this notification stack and display only selective information in our application
I hope my answer will help and solve your query
This answer is given at : enter link description here

how to send push Notifications to other device in android?

Using this code, i am able to send a notification to my own device.
Intent intent = new Intent(getApplicationContext(), ContactDonor.class);
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
//display text
String body = "Please Click on this to accept!";
String title = bloodgroup+" Required";
Notification n = new Notification(R.drawable.ic_launcher, body , System.currentTimeMillis());
n.setLatestEventInfo(getApplicationContext(), title, body, pi);
n.defaults = Notification.DEFAULT_ALL;
nm.notify(uniqueID, n);
finish();
But now i have a screen where a person's details are displayed like:
Name: ...
email: ...
, and there is a message box and a Request Button , on the click of that button, he should receive a notification with that particular message. How can this particular thing be done?
It cannot be implemented by using PUSH notifications. PUSH notification is useful when there is server-client comm is implemented where server notifies the client about the event that has occurred on server side.
What you are trying to implement indirectly is server-client architecture, where your device will act as server. If you mould your current architecture to server-client you will be able to send notification to other device. In this case also, you don't need PUSH notifications, it will be a simple server-client communication.
For more info on PUSH please see: http://www.vogella.com/articles/AndroidCloudToDeviceMessaging/article.html#c2dm_sendmessage
You can also send SMS, but that will not solve your problem. According to me, there is no other solution that you can apply to send notification.

Categories

Resources