GCM and Special characters - android

I recently changed my c2dm push aaplucation to GCM. A new problem appeared. Its now receiving '?' instead of 'ö','ï', ...
My server logs correct Strings, but the application receives '?' insteads.
Do you think it could have something to do with GCM?
My code is the following:
public static void displayMessage(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String message = (String) extras.get("message");
Log.v("extras", extras.toString());
Util.generateNotification(context, message, intent);
}
}
and the log is then:
10-02 22:18:23.671: V/intent(29809): Bundle[{message={"name":"j?rg"},
message_id=8bb60eee-3a93-4075-b606-40495511a4da, collapse_key=do_not_collapse, from=160085429222}]
Best regards!

I dont think so there is problem in GCM. Try to use UTFEncoding for your message.
String output = new String(name.getBytes("8859_1"), "utf-8");

Related

How to get message from GCM message body in 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.

Unit Testing Android SMS Receiver

i try to write an unit test on an BroadcastReceiver that gets informed when an SMS was received. Its not meant to be the default Application. Instead i just need this for an two factor authentication. For this case i created an PDU with [1].
But when i pass it down to the BroadcastReceiver the phone nr of the Sender never gets read by android it's just null. The body text is returned.
#TargetApi(Build.VERSION_CODES.KITKAT)
#Test
public void testOnReceive() throws Exception {
final byte[] decodedPDU = BaseEncoding.base16().decode(PDU);
final ReceiveSmsBroadcastReceiver receiveSmsBroadcastReceiver = spy(new ReceiveSmsBroadcastReceiver(true));
final Intent intent = new Intent();
intent.putExtra("format",SmsConstants.FORMAT_3GPP);
intent.putExtra("pdus", new Object[]{decodedPDU});
intent.setAction("android.provider.Telephony.SMS_RECEIVED");
intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, 1);
receiveSmsBroadcastReceiver.onReceive(InstrumentationRegistry.getTargetContext(), intent);
In the receiver i do this to get the SMSMessage Objects:
#TargetApi(Build.VERSION_CODES.KITKAT)
private void getSMSKitKat(final Context context, final Intent intent) {
final SmsMessage[] messagesFromIntent = Telephony.Sms.Intents.getMessagesFromIntent(intent);
I receive an SmsMessage array here, the body message is correct. But i need to test my check sender phone number before i can notify the UI that the SMS is received: But nr is always null here:
private boolean isCorrectSender(#Nullable final SmsMessage message) {
if (message == null) {
return false;
}
final String nr = message.getOriginatingAddress();
Can someone point me whats wrong here ?
PS: SMSConstants and PhoneConstants are all framework classes i took from AOSP to get it running because those APIs are non public
[1] http://twit88.com/home/utility/sms-pdu-encode-decode

Read content from notification parcelable objects for consequent notification

I am trying to build Whatsapp Notification filtering app, where I monitor all notification from Whatsapp and remove messages as per filtering policy.
I can fetch message content using below link code
Extract notification text from parcelable, contentView or contentIntent for first message only
but the problem is I can fetch only first message, if user does not read first message then second message onwards I get only "2 messages from sender" instead of actual message.
NOTE: I am getting
android.text = actual message for first message but its null from second message/notification onwards
android.title = sender
android.summaryText = "n new messages"
any help would be appreciated.
Yes, finally after few hours of googling I design a code which does work for me.
Bundle extras = sbn.getNotification().extras;
CharSequence[] lines = extras.getCharSequenceArray(Notification.EXTRA_TEXT_LINES);
JSONArray s = new JSONArray();
for (CharSequence msg : lines) {
msg = removeSpaces(msg);
if (!TextUtils.isEmpty(msg)) {
s.put(msg.toString());
}
}
private static String removeSpaces(#Nullable CharSequence cs) {
if (cs == null)
return null;
String string = cs instanceof String ? (String) cs : cs.toString();
return string.replaceAll("(\\s+$|^\\s+)", "").replaceAll("\n+", "\n");
}
here JSONArray s contains all messages that I want

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.

I can't receive my message in my Android Device through google cloud messaging?

I am using python as server app to send my message to GCM Server to receive on registered android device. I am getting success from GCM server with message id.
On android mobile I am receiving data in arg1 in onMessage() function but with just two keys in arg1, from & collapse_key.
In below Java Code, from key contains a LongInt value & message is null.
Can anybody tell me what thing i am missing in Java Code or in Python Code.?
Here is my JavaCode:
#Override
protected void onMessage(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
String keys="";
for (String key : arg1.getExtras().keySet())
keys+=key+"||";
String mess = arg1.getExtras().getString("from");
String mess1 = arg1.getExtras().getString("message");
}
Python Code:
def SelectAction(request,client_id):
if request.method == 'GET':
message = request.GET.get('message','')
if not message:
return Error(message = "Argument Missing.")
registration= Registration.objects.get(registeredUser = user)
values = {}
values['registration_id'] = registration.appId
values['data.message'] = message
param = urllib.urlencode(values)
req = urllib2.Request("https://android.googleapis.com/gcm/send", param)
req.add_header( 'Content-Type' , 'application/x-www-form-urlencoded;charset=UTF-8' )
req.add_header( 'Authorization' , 'key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
response = urllib2.urlopen(req)
reply = {}
if response.read().split('=')[0] == 'id':
reply['error'] = '0'
else:
reply['error'] = '1'
return HttpResponse(json.dumps(reply), mimetype="application/javascript")
else:
return Error()
Try extract the data before you do something else:
Bundle data = intent.getExtras();
if (data != null) {
data.isEmpty(); toString();
}
Now you can use toString(); and see what the data contains:
Log.i("C2DM", data.toString());
check the log for C2DM and paste what you get.
Everything seems to be set up correctly. It seems to me like that the message is never sent in the first place to your server. Since you can retrieve the from but not message, this is probably correct.
In the server, can you change the following line;
values['data.message'] = message
to this;
values['data.message'] = "testMessage"
I think this will most likely lead to you getting the message in android.. Just temporarily change the message to see if the push is working to begin with..

Categories

Resources