Sending upstream message to GCM from Android app - android

I am trying to send some data to GCM. I have configured xampp in my local server to accomplish that.
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
Bundle data = new Bundle();
String msgId = "001";
data.putString("myid", id);
data.putString("mylt", la);
data.putString("myln", lo);
data.putString("recid", recid);
gcm.send(recid+ "#gcm.googleapis.com", msgId, data);
} catch (IOException ioexce) {
ioexce.printStackTrace();
msg = ioexce.toString();
Log.e("gcm_error", msg);
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
}
}.execute(null, null, null);
Per the docs the parameters in the send method are, String to, String msgId, Bundle data. I used the token the receiver received when they register with GCM in place of String to. But I get "W/InstanceID/Rpc: Found 10011" in the log when I execute the above code and the message is not sent to my server. Upon some research I found out the "found 10011" meant some parameter is missing. But I don't know what is missing.

Related

How to pass a Bundle to another object (limited to AsyncTask Thread)?

I want to create a Bundle object for AsyncTask thread which remains unaffected by changes done to data (after passing it to sendMessage().
My code immediately removes a value in data after calling sendMessage() but I need that value to be sent to server.
Can someone suggest an efficient way, such that once data is passed (it gets copied, for the lack of better term) for the duration of sending message and gets destroyed on its own.
CODE
public void sendMessage(final Bundle data)
{
sendTask = new AsyncTask<Void, Void, String>()
{
#Override
protected String doInBackground(Void... params)
{
String id = Integer.toString(msgId.incrementAndGet());
try
{
Log.d(TAG, "message_id: " + id);
gcm.send(PROJECT_NUMBER + "#gcm.googleapis.com", id, data);
}
catch (Exception e)
{
Log.d(TAG, "Exception: " + e);
e.printStackTrace();
}
return "GCM send is a success";
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
sendTask = null;
Log.d(TAG, "Result = " + result);
Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
}
};
sendTask.execute();
}
You can pass data to doInBackground(), here are the steps:
Change parameter type accepted by AsyncTask sendTask = new AsyncTask<Bundle, Void, String>()
Now change protected String doInBackground(Void... params) to protected String doInBackground(Bundle... params)
You can access bundle using gcm.send(PROJECT_NUMBER + "#gcm.googleapis.com", id, params[0]);
Also change sendTask.execute(); to sendTask.execute(data); for passing it to Async Task.

Is it possible to understand notification comes from which client?

I send notification one client to another successfully. With this method:
ParsePush push = new ParsePush();
String yourMessage = "hello world";
push.setChannel("seconddevice");
push.setMessage(yourMessage);
push.sendInBackground();
my application:
public class ParseApplication extends Application {
String YOUR_APPLICATION_ID="xxx",YOUR_CLIENT_KEY="yyy";
#Override
public void onCreate() {
super.onCreate();
// Add your initialization code here
Parse.initialize(this, YOUR_APPLICATION_ID, YOUR_CLIENT_KEY);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// If you would like all objects to be private by default, remove this line.
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
PushService.subscribe(this, DEVICE_NAME, NotificationBck.class);
}
}
It works. But when I receive message in second device can I have which device send this notification?
From the Parse Android docs:
The Intent object which is passed to the receiver contains an extras Bundle with two useful mappings. The com.parse.Channel key points to a string representing the channel that the message was sent on. The com.parse.Data key points to a string representing the JSON-encoded value of the "data" dictionary that was set in the push notification.
So, in your receiver, you'd be able to check the data (assuming you've set it when pushing):
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String channel = intent.getExtras().getString("com.parse.Channel");
String encodedJson = intent.getExtras().getString("com.parse.Data");
Log.d(TAG, "got action " + action + " on channel " + channel + " with:");
JSONObject json = decodeJsonObjectFrom(encodedJson);
logContentsOf(json);
}
private JSONObject decodeJsonObjectFrom(String encodedJson) {
try {
return new JSONObject(encodedJson);
} catch (JSONException e) {
return new JSONObject();
}
}
private void logContentsOf(JSONObject json) {
while (json.keys().hasNext()) {
String key = (String) json.keys().next();
Log.d(TAG, "..." + key + " => " + getStringFrom(json, key));
}
}
private String getStringFrom(JSONObject json, String key) {
try {
return (String) json.get(key);
} catch (JSONException e) {
return "";
}
}

quickblox, how to retrieve custom parameters in chat?

i'm developing an android application using quickblox api. I'm using chat SMACK functionality (1 to 1 chat) and i try receive message from chat. I can retrieve the message text, but i can't get customs parameters.
Here is a screen about my message variable:
The values i need are values stored in 'map' : tempo, telefono, stato, nome , prefisso.. how i can retrieve that? I just try to search on quickblox documentation, but i have an api error when try to implement DefaultPacketExtension.
Thank you
Here is an example how to do it using QuickBlox Android SDK 1.1
To send message with additional parameters:
Map<String, Object> addinfoParams = new HashMap<String, Object>();
addinfoParams.put(Consts.AGE, 22);
addinfoParams.put(Consts.TYPE, "actor");
final String BODY = "Hey QuickBlox!";
Message message = createMsgWithAdditionalInfo(USER_ID, BODY, addinfoParams);
Log.i(TAG, "message: " + message.toXML());
try {
qbPrivateChat.sendMessage(USER_ID, message);
} catch (XMPPException e) {
e.printStackTrace();
}
...
private Message createMsgWithAdditionalInfo(int userId, String body, Map<?, ?> addinfoParams){
Message message = new Message(QBChatUtils.getChatLoginFull(userId), Message.Type.chat);
String addInfo = ToStringHelper.toString(addinfoParams, "", Consts.ESCAPED_AMPERSAND);
MessageExtension messageExtension = new MessageExtension(Consts.QB_INFO, "");
try {
messageExtension.setValue(Consts.ADDITIONAL_INFO, addInfo);
} catch (BaseServiceException e) {
e.printStackTrace();
}
message.addExtension(messageExtension);
message.setBody(body);
return message;
}
To receive message and get custom parameters:
chatMessageListener = new ChatMessageListener() {
#Override
public void processMessage(Message message) {
String from = message.getFrom();
String messageBody = message.getBody();
List<MessageExtension> messageExtensions = message.getExtensions();
}
#Override
public boolean accept(Message.Type type) {
switch (type) {
case normal:
case chat:
case groupchat:
return true;
default:
return false;
}
}
};
More info in Chat snippets https://github.com/QuickBlox/quickblox-android-sdk/blob/master/snippets/src/com/quickblox/snippets/modules/SnippetsChat.java

Delivery receipt requests not working for XMPP Android (aSmack)

I'm using OpenFire with aSmack.
I can't seem to get DeliveryReceipts working.
I do the following when I create a connection:
//create connection
connection.login(username, password);
DeliveryReceiptManager.getInstanceFor(connection).enableAutoReceipts();
DeliveryReceiptManager.getInstanceFor(connection).addReceiptReceivedListener(new ReceiptReceivedListener()
{
#Override
public void onReceiptReceived(String arg0, String arg1, String arg2)
{
Log.v("app", arg0 + ", " + arg1 + ", " + arg2);
}
});
I'm sending a message to another user using:
//send chat
Message msg = new Message(id, Message.Type.chat);
msg.setBody(chat);
DeliveryReceiptManager.addDeliveryReceiptRequest(msg);
connection.sendPacket(msg);
The above does not work although the message gets sent with the ReceiptRequest. The listener does not get fired at the sender's end although the receiver receives the message. (I confirmed it through debugging that a DeliveryReceiptRequest does indeed get attached to the message that is sent).
I've also tried manually sending back the Receipt by using the following in my PacketListener with (MessageTypeFilter(Message.Type.chat)):
Packet received = new Message();
received.addExtension(new DeliveryReceipt(packet.getPacketID()));
received.setTo(packet.getFrom());
getConnection().sendPacket(received);
Still, the client at the receiving end receives the message alright but the listener does not get fired in the sender's system. Anything I'm missing?
Add these lines before you set up your connection and Auto Receipts will work with ReceiptReceivedListener. Seems like the DeliveryReceipt extensions aren't registered by default.
ProviderManager.getInstance().addExtensionProvider(DeliveryReceipt.ELEMENT, DeliveryReceipt.NAMESPACE, new DeliveryReceipt.Provider());
ProviderManager.getInstance().addExtensionProvider(DeliveryReceiptRequest.ELEMENT, new DeliveryReceiptRequest().getNamespace(), new DeliveryReceiptRequest.Provider());
Hi the above said answer given me NPE, so I used following code to get message notifications which was working perfectly for me:
Don't forget to add this ProviderManager
ProviderManager pm = ProviderManager.getInstance();
pm.addExtensionProvider("x", "jabber:x:event",new MessageEventProvider());
MessageEventManager messageEventManager = new MessageEventManager(connection);
messageEventManager.addMessageEventNotificationListener(m_messageEventNotificationListener);
messageEventManager.addMessageEventRequestListener(m_DefaultMessageEventRequestListener);
/*
* Notifies when message events happend
*
*/
MessageEventNotificationListener m_messageEventNotificationListener = new MessageEventNotificationListener() {
#Override
public void deliveredNotification(String fromJID, String messageID) {
final String _messageID =messageID;
System.out.println("deliveredNotification");
UiUtility.printMe("Message("+messageID+") Was Delivered to "+fromJID);
//WRITE YOUR CUSTOM METHOD WHEN MSG DELIVERED NOTFICATIONN RECIEVED.
}
#Override
public void displayedNotification(String string, String string1) {
}
#Override
public void composingNotification(String string, String string1) {
}
#Override
public void offlineNotification(String string, String string1) {
}
#Override
public void cancelledNotification(String string, String string1) {
}
};
/*
* Send a request when message events occured
*/
DefaultMessageEventRequestListener m_DefaultMessageEventRequestListener = new DefaultMessageEventRequestListener() {
#Override
public void deliveredNotificationRequested(String from, String packetID, MessageEventManager messageEventManager) {
super.deliveredNotificationRequested(from, packetID, messageEventManager); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void displayedNotificationRequested(String from, String packetID, MessageEventManager messageEventManager) {
super.displayedNotificationRequested(from, packetID, messageEventManager); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void offlineNotificationRequested(String from, String packetID, MessageEventManager messageEventManager) {
super.offlineNotificationRequested(from, packetID, messageEventManager); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void composingNotificationRequested(String from, String packetID, MessageEventManager messageEventManager) {
super.composingNotificationRequested(from, packetID, messageEventManager); //To change body of generated methods, choose Tools | Templates.
}
};
It's a bit late but this will help someone, take note of
receiptManager.setAutoReceiptMode(DeliveryReceiptManager.AutoReceiptMode.always);
Check below code:
DeliveryReceiptManager receiptManager = DeliveryReceiptManager.getInstanceFor(connection);
//automatically enable delivery receipts to every message
receiptManager.autoAddDeliveryReceiptRequests();
receiptManager.setAutoReceiptMode(DeliveryReceiptManager.AutoReceiptMode.always);
receiptManager.addReceiptReceivedListener(new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(Jid fromJid, Jid toJid, String receiptId, Stanza receipt) {
//handle delivery receipts here
}
});

One Android chat app unable to receive messages ( aSamck + Openfire )

I have implemented a chat application using aSmack. I used the openfire server as the chat server. All of these applications are running in the same machine. But when I try to send messages between two emulators only one emulator successfully receives messages. Other client won't receive any messages. But from both emulators I was able to send messages to pigin(IM clinet). Also if I use gmail.com as the chat server everything works just fine.
User names used to login
jayamal
suchith
(openfire indicates users are online )
names used to send messages
jayamal#elearn (elearn is the domain i created in my machine using openfire)
suchith#elearn
( but in openfire archives shows one name as jayamal#elearn/Smack, tried sending message to that name but it also unsuccessful )
Please help to rectify this problem. Your help is really appreciated.
public class ASmackChatTestActivity extends Activity {
public int state = 0;
private static final String TAG = "HelloFormStuffActivity";
XMPPConnection xmpp ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnLogin = (Button) findViewById(id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText txtUserName = (EditText) findViewById(id.txtUserName);
EditText txtPass = (EditText) findViewById(id.txtPass);
String userName = txtUserName.getText().toString();
String password = txtPass.getText().toString();
new login().execute(userName,password);
}
});
Button btnSend = (Button) findViewById(id.btnSend);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText txtMessage = (EditText) findViewById(id.txtMessage);
EditText txtTo = (EditText) findViewById(id.txtTo);
String message = txtMessage.getText().toString();
String to = txtTo.getText().toString();
new sendMessage().execute(to,message);
}
});
Button btnStop = (Button) findViewById(id.btnStopServices);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText txtTo = (EditText) findViewById(id.txtTo);
String to = txtTo.getText().toString();
new recieveMessages().execute(to);
}
});
}
class login extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String userName = params[0];
String password = params[1];
//XMPPConnection xmpp = new XMPPConnection("jabber.iitsp.com");
xmpp = new XMPPConnection("10.0.2.2");
try {
xmpp.connect();
// for other jabber accounts, truncate after the #
//xmpp.login("username", "password");
// for gtalk / gmail, include the #
xmpp.login(userName, password);
Log.v(TAG,"Logged in");
} catch (XMPPException e) {
Log.v(TAG, "Failed to connect to " + xmpp.getHost());
e.printStackTrace();
}
return null;
}
}
class sendMessage extends AsyncTask<String, Void, String>{
//String msg;
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String to = params[0];
String message = params[1];
ChatManager chatmanager = xmpp.getChatManager();
Chat newChat = chatmanager.createChat(to, new MessageListener() {
// THIS CODE NEVER GETS CALLED FOR SOME REASON
public void processMessage(Chat chat, Message message) {
try {
// msg = message.getBody();
Log.v(TAG, "Got:" + message.getBody());
chat.sendMessage(message.getBody());
} catch (XMPPException e) {
Log.v(TAG, "Couldn't respond:" + e);
}
Log.v(TAG, message.toString());
}
});
// Send something to friend#gmail.com
try {
newChat.sendMessage(message);
Log.v(TAG, "sent:" + message);
} catch (XMPPException e) {
Log.v(TAG, "couldn't send:" + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(),"Message Recieved : " + msg, Toast.LENGTH_LONG);
super.onPostExecute(result);
}
}
class recieveMessages extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String to = params[0];
// Accept only messages from friend#gmail.com
PacketFilter filter
= new AndFilter(new PacketTypeFilter(Message.class),
new FromContainsFilter(to));
// Collect these messages
PacketCollector collector = xmpp.createPacketCollector(filter);
while(true) {
Packet packet = collector.nextResult();
if (packet instanceof Message) {
Message msg = (Message) packet;
// Process message
Log.v(TAG, "Got message: " + msg.getBody());
}
}
//return null;
}
}
}
Sorry this is a bit late.
The one user you can send to the IM client (pidgin) can you send back to your emulator. I.e. can you receive in either emulator?
Message receiving is event based so you don't need to use a button click to set it off.
Check out this great example. By Davanum Srinivas
I've modified it for my use quite extensively but the base code is still very useful.
http://davanum.wordpress.com/2008/12/29/updated-xmpp-client-for-android/ also look at the original article.

Categories

Resources