Sending push notification using Parse SDK on Android - android

I am trying to do ChatApp. I can do talking people each other. But there is an issue. I want to use push notification when a message sended to any user.
So i am adding these information. I have these classses on Parse.
Intallation , Session , User, Chat.
I am using User class for users , Chat class for each conversation for example someone senf a message another one , i am adding an object my chat class.
So I dont know how can i send push notification. I guess i should use User objectId to finding buddy. And here i am adding my sendMessage method:
private void sendMessage() {
if (txt.length()==0)
return;
InputMethodManager imm= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txt.getWindowToken(), 0);
String s=txt.getText().toString();
final Conversation c=new Conversation(s,new Date(),UserList.user.getUsername());
c.setStatus(Conversation.STATUS_SENDING);
convList.add(c);
adp.notifyDataSetChanged();
txt.setText(null);
ParseObject po=new ParseObject("Chat");
po.put("sender",UserList.user.getUsername());
po.put("receiver",buddy);
po.put("message",s);
po.saveEventually(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null){
c.setStatus(Conversation.STATUS_SENT);
}
else {
c.setStatus(Conversation.STATUS_FAILED);
}
adp.notifyDataSetChanged();
}
});
}

Use the below code to send the push notification:
public void sendpushnotification(String buddyObjectId,String message,String type,String chatObjectID){
ParseQuery query = ParseInstallation.getQuery();
query.whereEqualTo("owner",owner);
ParsePush push = new ParsePush();
push.setQuery(query);
try {
JSONObject data = new JSONObject("{\"action\": \"{Action name}\",\"alert\":\""+message+"\",\"mid\":\""+chatObjectID+"\",\"pid\":\""+chatObjectID+"\",\"t\": \""+type+"\"}");
push.setData(data);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
push.sendInBackground();
}
Where buddyObjectId is buddy object id
chatObjectID is chat message object id after saving
type is type of message if any.
Also make sure to save user object id in owner column of the installation table when a user is created.

Related

Send push notification to other user in publish chat group quickblox

i'm using quickblox SDK in my project .
And i have a question about that.
Plz advise
I want to send push notification to other user in PUBLIC chat group.
I can do it with private chat by creating an event and sent to friend like this
public void createEvent(String message, List<Integer> userIds) {
StringifyArrayList<Integer> userIds_ = new StringifyArrayList<Integer>(userIds);
QBEvent event = new QBEvent();
event.setUserIds(userIds_);
event.setEnvironment(QBEnvironment.PRODUCTION);
event.setNotificationType(QBNotificationType.PUSH);
HashMap<String, Object> messageData = new HashMap<>();
messageData.put("message", message);
messageData.put("firID", KApp.getInstance().getCurrentUser().getId());
messageData.put("name", KApp.getInstance().getCurrentUser().getName());
event.setMessage(messageData);
QBPushNotifications.createEvent(event).performAsync(new QBEntityCallback<QBEvent>() {
#Override
public void onSuccess(QBEvent qbEvent, Bundle bundle) {
System.out.print("Create event success");
System.out.print(qbEvent.toString());
}
#Override
public void onError(QBResponseException e) {
System.out.print("Create event error : " + e.getLocalizedMessage());
}
});
}
But with PUBLIC chat dialog , i can't get list user id, it alway return empty.
How can i send push notification to other member in PUBLIC group ?
There is no sense in sending pushes to PUBLIC_GROUP because all users can chatting in public group chat. If you need notify occupants of dialog, use GROUP dialog. Note: in PUBLIC_GROUP you will also not receive pushes about messages when user is offline because PUBLIC_GROUP dialog not contain occupants_ids.
PUBLIC_GROUPS are open group. The difference between GROUP and PUBLIC_GROUP is that it does not keep associated participant's records like user_ids or unread_count . You have to store your participants data in your own backend server or else locally.

Send device to device push notification using parse.com

I am new to parse. I have created an android application in which I have to send the push notification by click on the send button. I have successfully stored data to its parse database like Object Id, device type, device token, push type (which is created by default under the installation class).
I have also add some custom column under installation class like age, friend id, gender and retrieve the correspondence Object id in the edit text.
But when I try to send push notification by click on send button, I usually get this error:
com.parse.Parse Exception: Clients aren't allowed to perform the find operation on the installation collection
The query which I am using to send push notification with object-id corresponding to the given Friend-id is:
sndpush.setOnClickListener(new OnClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onClick(View v) {
JSONObject obj;
try {
obj =new JSONObject();
obj.put("alert","erwerwe");
obj.put("action","com.parse.pushnotifications.UPDATE_STATUS");
obj.put("customdata","My string");
ParsePush push = new ParsePush();
ParseQuery query = ParseInstallation.getQuery();
query.whereEqualTo("objectId",objectidEditText.getText().toString() );
push.setQuery(query);
push.setData(obj);
push.sendInBackground();
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
I do google and R&D and I get the idea that we have no permission to send push by get the object id from default class that is installation class.
I have created a new class in parse.com where I have insert some data like age, friend-id and also able to retrieve object-id corresponding to friend id. But when ever I tried to send push notification by supplying Object-id in it, I get the error:
java.lang.IllegalArgumentException: Can only push to a query for Installations
Here is the code:
// Get the user's Id from parse.com.
#SuppressWarnings({ "rawtypes", "unchecked" })
public void getObjectId() {
#SuppressWarnings("rawtypes")
ParseQuery query = new ParseQuery("_installation");
query.whereEqualTo("FriendId", FrndTextString);
query.getFirstInBackground(new GetCallback() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
Log.d("objectId", "The getFirst request failed.");
} else {
String objectid = object.getObjectId();
objectidEditText.setText(objectid);
sndpush.setEnabled(true);
Log.d("objectId", "Retrieved the object.");
}
}
});
}
I have followed the link from stack overflow to send push notification to a specific user. But there is no proper result.
send push notification with parse to single device
Please tell me where I am wrong. My main question is how can I send a push notification from one device to another.
Here is my complete code:
http://piratepad.net/ep/pad/view/ro.WwZ9v6FX1a6/latest

can't send push notification from a device-parse

I'm trying to add the feature of push notifications in my app and i did everything correctly according to many guides but the push is never being sent (i don't see it in the push list in parse). On the contrary, when i send a push from parse to a specific channel( which is exactly what i want to do from the device), i do get a message on devices which subscribed to that channel.
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParsePush push = new ParsePush();
push.setQuery(query);
push.setChannel(listId);
push.setMessage("Hey pal"+", it looks like "+cur_user.getUsername()+" added you to a new list."+" Log in to check it.");
push.sendInBackground(new SendCallback() {
#Override
public void done(ParseException e) {
if(e == null){
Log.d("DONE BUTTON","im here");
onBackPressed();
}else{
Log.d("PUSH ERROR",e.toString());
}
}
});
}
});
//update the list on the screen
updateData();
}
I literally have no idea why it doesn't work.
listId which sent to setChannel is a valid channel (I checked that) and it is included in the channels column in several installations in parse among other channels (i mean, i have installations with more than one channel and i want to send this message onlt to listId channel).

Android Basic Push Notification Send from client side doesn't work

I'm looking for some help with push notifications on Android.
Situation:
I'm trying to do a push send from an Android device, at this time for itself ( will understand later) but when I hit the send button nothing happens
Config:
Firstly, yes, the client side push is enabled.
Secondly my onCreate method in the "extends Application" class
public void onCreate() {
super.onCreate();
//Parse
//Parse.enableLocalDatastore(this);
Parse.initialize(this, "", "");
ParseObject.registerSubclass(Groups.class);
ParseObject.registerSubclass(Users.class);
//Subscribe to push
ParsePush.subscribeInBackground("", new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.d("com.parse.push", "successfully subscribed to the broadcast channel.");
} else {
Log.e("com.parse.push", "failed to subscribe for push", e);
}
}
});
// Save the current Installation to Parse.
ParseInstallation.getCurrentInstallation().saveInBackground();
}
My button to send the push notification ( its the basic code from the docs )
sendReqBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Debug push onclick");
ParsePush push = new ParsePush();
push.setChannel("");
push.setMessage("The Giants just scored! It's now 2-2 against the Mets.");
push.sendInBackground(new SendCallback() {
#Override
public void done(ParseException e) {
System.out.println("Push send done");
}
});
}
});
All other settings set by the basic android tutorial (Like manifest and basic sdk adding, I already use other parse functions)
So after this code snippets added to my app I hoped that I will get a notification on the device itself as described earlier, but nothing happens. From the parse push dashboard I tried it, and it works fine (thats why I think the manifest and other things are configured well) and in the core panel on the dashboard i can see the installation in the list and the "" mark in the channels array.
Can anyone help me out?
Thanks in advance!!
Steve

Usage of Parse's Local datastore feature for caching of messages

Situation
I write an Android messaging app using Parse.com as back-end
There's an activity showing list of messages sent to currently logged in user
User gets push from Parse if there is new message for him on the server
I try to accomplish this in two steps:
When this activity starts (in its onCreate method), I fetch all messages for current user from Parse back-end end store them into local datastore, if there were any messages already in the datastore, they all are removed (unpinned) and the fetched messages are pinned instead
Then I ask the local datastore for the messages and with the results I refresh the list of messages (by filling ArrayList<Message> variable and calling notifyDataSetChanged on the adapter using this variable as source of data)
Why in two steps?
I have it split into two steps, because when the activity is running and user receives from Parse back-end a push that there is/are new message(s) for him, I fetch only the new messages in similar way (but not exactly like) in step 1., and then call the exact same refresh function like in step 2. For this a broadcast receiver handling the pushes is used
Step 1.
The following code snippet shows how I fetch all messages from server in step 1 in the onCreate method of the activity
ParseQuery<Message> query = ParseQuery.getQuery(Message.class);
query.whereEqualTo("recipient", ParseUser.getCurrentUser());
query.addDescendingOrder("createdAt");
query.findInBackground(new FindCallback<Message>() {
#Override
public void done(final List<Message> messages, ParseException e) {
if (e == null && messages.size() > 0) {
ParseObject.unpinAllInBackground("messages",
new DeleteCallback() {
#Override
public void done(ParseException e) {
ParseObject.pinAllInBackground("messages",
messages, new SaveCallback() {
#Override
public void done(
ParseException e) {
for (Message message : messages) {
if (message.getStatus() == 0) {
message.setStatus(1);
message.saveEventually();
}
}
refreshList();
}
});
}
});
}
}
});
The part when status is changed from 0 to 1 is to change the message from being new to unread
For sake of completeness and to document the words written in Why in two steps?, this is how I get only the new messages in the onReceive of the broadcast receiver processing the pushes from Parse back-end
Broadcast receiver snippet
public void onReceive(Context context, Intent intent) {
ParseQuery<Message> query = ParseQuery.getQuery(Message.class);
query.whereEqualTo("recipient", ParseUser.getCurrentUser());
query.whereEqualTo("status", 0);
query.addDescendingOrder("createdAt");
query.findInBackground(new FindCallback<Message>() {
#Override
public void done(final List<Message> messages, ParseException e) {
if (e == null && messages.size() > 0) {
ParseObject.pinAllInBackground("messages", messages,
new SaveCallback() {
#Override
public void done(ParseException e) {
for (Message message : messages) {
message.setStatus(1);
message.saveEventually();
}
refreshList();
}
});
}
}
});
}
Step 2. The refreshList function
private void refreshList() {
ParseQuery<Message> query = ParseQuery.getQuery(Message.class);
query.fromPin("messages");
query.whereEqualTo("recipient", ParseUser.getCurrentUser());
query.addDescendingOrder("createdAt");
query.findInBackground(new FindCallback<Message>() {
#Override
public void done(final List<Message> messages, ParseException e) {
items.clear();
for (Message m : messages) {
items.add(m);
}
adapter.notifyDataSetChanged();
}
});
}
Other variables
ArrayList<Message> items;
MessageArrayAdapter adapter;
Where MessageArrayAdapter just extends ArrayAdapter
Why do I need to use the local datastore at all?
The activity can exist for quite long time
... and the user can receive new messages when the activity is running
I don't want to ask the server every time there is new message for all messages
I know I could ask just for the new ones and add them to the items when it is member variable of the activity where all this happening. In such case, I didn't have to use the local datastore at all
The reason for using it is that in the future I plan to move the fetch all messages from the activity completely - e.g. to start of whole application or maybe to service fetching the messages on periodic basis
Is this acceptable way of solving this problem?

Categories

Resources