How to get message from GCM message body in android? - android

I have an app in which server sends some push notification using GCM server, The implementation is done on both side but i am facing problem is that i can't get notification from message body, it is always showing me "null". But i can see message in messag body using debug.
String message = bundle.getString("message");
Log.e(TAG, "onMessageReceived::" + message);
Log.e(TAG, "from::" + from);
and message body is :-
Bundle[{google.sent_time=1497866966996, google.message_id=0:1497866967011288%466cbbd8466cbbd8, notification=Bundle[{priority=high, body=Your wallet has been credited with 1.000 point(s)., title=Wallet credited}], collapse_key=com.s.baty}]

Try ,
Bundle notificationData = bundle.getBundle("notification");
String body = notificationData.getString("body");

It received correct data only
String bodymessage = bundle.getString("body");
Problem is print message after converting Sting
Log.e(TAG, "onMessageReceived::" + message.toString());

You can receive message in onMessage() function of GCMIntentService implementing class. I have created a function for getting proper message and key.
#Override
protected void onMessage(Context context, Intent intent) {
dumpIntent(intent);
}
public void dumpIntent(Intent i) {
Bundle bundle = i.getExtras();
if (bundle != null) {
Set<String> keys = bundle.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String key = it.next();
Log.e("Intent Data", "[" + key + "=" + bundle.get(key) + "]");
}
}
}
After that you will easily set message with NotificationManager.

Related

how to push message/notification to every subscriber of One Signal

i can push notification to a specific user using its id (notification key)
public class SendNotification {
public SendNotification(String message, String heading, String notificationKey){
try {
JSONObject notificationContent = new JSONObject(
"{'contents':{'en':'" + message + "'},"+
"'include_player_ids':['" + notificationKey + "']," +
"'headings':{'en': '" + heading + "'}}");
OneSignal.postNotification(notificationContent, null);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
as in one signal documentation
https://documentation.onesignal.com/docs/sending-notifications
there we can push notification to everyone(all the subscribers)
how can i push notification to everyone using code as i can send to a single subscriber
Send to all Active Users with the included_segments key:
Update:
It seems like using include_player_ids does not require an API Key to send the message. However, using included_segments, does - "Requires your OneSignal App's REST API Key"
Have ammended the code below to include the app_id key.
public class SendNotification {
public SendNotification(String message, String heading, String notificationKey){
try {
JSONObject notificationContent = new JSONObject(
"{'app_id':\"YOUR_APP_ID\"," +
"'contents':{'en':'" + message + "'},"+
"'included_segments':[\"Active Users\"]," +
"'headings':{'en': '" + heading + "'}}");
OneSignal.postNotification(notificationContent, null);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
https://documentation.onesignal.com/reference#section-example-code-create-notification

How to send hidden SMS on android 6.0+ [duplicate]

I have an auto reply sms Android application I built and I don't want the auto reply (sent sms) to show in the default messaging app. I have searched and searched and couldn't find an answer. Is there a way to bypass writing the sent sms into the default messaging app?
Here my BroadcastReciever I am using to get the data and send out the message
public class SmsReceiver extends BroadcastReceiver {
ParseUser user = ParseUser.getCurrentUser();
// Auto reply message composed of the current reply and url from that business
String msg = user.getString("myCurrentReply") + " " + user.getString("couponUrlChosen");
List smsFromList = user.getList("smsFrom");
String userName = (String) user.get("username");
#Override
public void onReceive(final Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
}
final String pno = smsMessage[0].getOriginatingAddress();
user.put("lastSmsFrom", pno);
user.saveInBackground();
// show first message
Toast toast = Toast.makeText(context, "Received SMS: " + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
toast.show();
// Check Phone Number from SMS Received against Array in User Row
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
Log.d("Username: ", userName);
query.whereEqualTo("username", userName);
query.whereContainedIn("lastSmsFrom", smsFromList);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> smsList, ParseException e) {
if (e == null) {
Log.d("Errors", "none");
if (smsList.size() == 0) {
// Send SMS
sendSms(pno, msg);
// Add Phone number to smsFrom in currentUsers Row
user.addUnique("smsFrom", pno);
// Save Phone Number in Array
user.saveInBackground();
Log.d("List size: ", " " + smsList.size());
}
} else {
Log.d("Error Message: ",
e.getMessage());
}
Log.d("Already sent to this number today. ", " " + smsList.size());
}
});
}
private void sendSms(String phonenumber, String message) {
SmsManager manager = SmsManager.getDefault();
manager.sendTextMessage(phonenumber, null, message, null, null);
}
}
Prior to KitKat, SMS sent using SmsManager require the app sending the message to insert it into the Provider, so it would just be a matter of omitting that.
Starting with KitKat, any app that is not the default SMS app and uses SmsManager to send messages will have the messages automatically written to the Provider for it by the system. There's no way to prevent this, and, furthermore, the app won't be able to delete those messages, either, as it won't have write access to the Provider.*
The app that is the default SMS app is responsible for writing its outgoing messages, so it would be able to omit that step. The system does no automatic writes for the default SMS app.
* There is a security hole in 4.4 only, by which a non-default app can gain write access to the Provider. It is detailed in my answer here, but it will not work in versions after KitKat.

not getting data when sending Push Notification with Parse Android

I am using PushService.subscribe(context,channel,NotificationActivity.class) to subscribe to the channel to get the push notification. I am able to get the push notification but not able to get the additional data in NotificationActivity. Here is my code.
JSONObject data = new JSONObject();
data.put("action","com.example.myapp.UPDATE_STATUS")
data.put("postTitle",result.get(0).getTitle() );
data.put("description", result.get(0).getDescription());
ParsePush push = new ParsePush();
push.setChannel(tag);
push.setData(data);
push.setMessage("Meassge sent is"+tag);
push.send();
NotificationActivity
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
ParseAnalytics.trackAppOpened(getIntent());
Intent intent = getIntent();
Bundle extras = intent.getExtras();
JSONObject jsonData1;
jsonData1 = new JSONObject(intent.getExtras().getString( "com.parse.Data" ));
while (itr.hasNext()) {
String key = (String) itr.next();
Log.d("NotificationActivity Logs", "..." + key + " => " + jsonData1.getString(key));
}
In the output (Logcat) I am only getting two keys. alert and push_hash, but not giving any other key which I set like title and description.

node-gcm sending successfully but I do not know how to get the data from the client side

So I am sending on the server side like so, using node-gcm
(https://github.com/ToothlessGear/node-gcm):
var gcm = require('node-gcm');
var message = new gcm.Message({
collapseKey: 'demo',
delayWhileIdle: true,
timeToLive: 3,
data: {
type: 'pong',
message: 'Hello Android!'
}
});
var sender = new gcm.Sender(myAPIKey);
var registrationIds = [aDoc.registrationId];
sender.send(message, registrationIds, 4, function (err, result) {
console.log(result);
});
And then on the client side, in my BroadcastReceiver, I get the Logcat message printing and the receive notification, but the extras (from the intent.getStringExtra("data") is null. How do I get it properly? I cannot find how to do it anywhere. The registration case works perfectly.
#Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
Log.i(TAG, "GCM Received");
switch(action){
case GCM.ACTION_REGISTRATION:
String registrationId = intent.getStringExtra(GCM.KEY_REG_ID);
Log.i(TAG, "action received: registration: " + registrationId);
...
break;
case GCM.ACTION_RECEIVE:
String extras = intent.getStringExtra("data");
Log.v(TAG, "" + extras);
...
...
extras is consistantly null
Through experimentation, I have solved my problem. Instead of accesssing the data object directly, node-gcm adds the key-value pairs to the intent's extras directly:
Wrong:
// returns null
String dataJson = intent.getStringExtra("data");
Right:
// returns "pong"
String type = intent.getStringExtra("type");

getting same message in android GCM

My android app getting same message like "you got message". Even though i'm changing data in server side.
Server-Side code(dot net):
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
+ Label1.Text + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + regId + "";
have to make any changes in GCM app code?
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = getString(R.string.gcm_message);
//String message = intent.getExtra("message");
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
On seraching google i found something that we have to replace this
String message = getString(R.string.gcm_message);
with
String message = intent.getExtra("message");
but i am getting error like this "The method getExtra(String) is undefined for the type Intent".Please guide me that what i'm missing in this?
use
String message = intent.getStringExtra("message");
instead of
String message = intent.getExtra("message");
for Getting String Message from Intent
EDIT :
if you are receive data in Bundle instance then change your code as because getExtra is not a method in Intent class :
Bundle bundle = intent.getExtras("bundle_Name_here");
now retrieve all value from bundle using key
Add this to your HTTP POST:
data.notId="2"
For each different notId it will be threated as a different message. I had the same problem for a long time, now I would like to group those messages.

Categories

Resources