I am creating an android application where I need to send gcm messages.
So far I managed to get device id and to sent it to my server.
Now when I'm trying to push a message from my server to my app, I receive this message : {"multicast_id":4987023356709284342,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1430085972465424%73c650e3f9fd7ecd"}]}, but nothing happens on the device (doesn't matter if the app is running or not).
Here is my relevant code:
Manifest.xml----------------- AndroidManifest.xml
BroadcastReceiver-------- GcmBroadcastReceiver
IntentService---------------- GcmIntentService
Register---------------------- GcmRegister
here I am using the register class (look for 'GCM HERE' tag)
LoginActivity---------------- LoginActivity
here is my android project structure
Structure--------------------- structure
Server side [PHP]
GcmPush ------------------- GcmPush.php
and this is how I'm using GcmPush.php
SendMessage-------------- send function
Hope someone can help me.
To point what I'm doing wrong....
Thank you!
Finally I found...
I put logs in GcmReceive, and it prints the log :), then I went to IntentServices, and there I found that the message has arived but notification didn't actually notify the message.
So far I didn't found yet what the problem is with my notification but, I think is something wrong with this line :
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
I am glad that the biggest problem is solved. Now I am searching arround what I'm doing wrong with Notification.
Thanks very much to everyone who tried to help...
Kindly refer the tutorial of GCM here. According to me you are missing the configuration file of GCM which has the APP_SERVER_URL, GOOGLE_PROJECT_ID.
Related
I m Trying to send a push notification to IOS Device.
My code like that for send a notification to ios device.
if($db_to[0]['platform']=='1') {
$messagesArray[]=array(
'DeviceToken'=>$db_to[0]['device_id'],
'Message'=>$msg,
'Sound'=>'default',
'noti_status'=>$db_to[0]['noti_status'],
'Type'=>'1',
'pid'=>$Promotion[0]['pid'],
'rest_id'=>$Promotion[0]['rest_id'] ,
'pnm'=>$Promotion[0]['pname'] ,
'pimg'=>$Promotion[0]['pimage'] ,
'pdesc'=>$Promotion[0]['pdesc'] ,
'p_bk_img'=>$Promotion[0]['p_background_img'] ,
'p_d_img'=>$Promotion[0]['p_detail_img'] ,
);
}
In PHP side I got these type of array when I printed the $messagesArray array.
But in IOS side he/she was got the different response like that.
aps = {
alert = "sent you a Notification";
sound = default;
type = 1;
};
So my Question is that , is there any changes in to the apns file or dataservice api files ???
IOS got only Type and Sound , and Notification Message which one I Send.
they didn't get the whole response which I was print it my side.
so Guys Please help me.
How can I Solve these.
Thanks in advance.
yes, which parameters you want in response just pass all parameters in function..
I'm using codeigniter-gcm library on top of codeigniter to send messages to Google Cloud Messaging service. It sends the message and the message is received at the mobile device, but if I send multiple messages, only the latest message appears on the device (as if it is overriding the previous messages).
I'm seeing that I might need to create a unique notification ID, but I'm not seeing how it's done anywhere on the codeigniter-gcm documentation or Google's documentation for downstream messages.
Any idea how this should be done?
Here's my code in the codeigniter controller. It is worth mentioning that Google's response contains a different message_id for each time I send a push...
public function index() {
$this->load->library("gcm");
$this->gcm->setMessage("Test message sent on " . date("d.m.Y H:i:s"));
$this->gcm->addRecepient("*****************");
$this->gcm->setData(array(
'title' => 'my title',
'some_key' => 'some_val'
));
$this->gcm->setTtl(false);
$this->gcm->setGroup(false);
if ($this->gcm->send())
echo 'Success for all messages';
else
echo 'Some messages have errors';
print_r($this->gcm->status);
print_r($this->gcm->messagesStatuses);
}
After three exhausting days I found the solution. I'm posting it here in hope of saving someone else's time...
I had to add a parameter to the data object inside the greater JSON object, named "notId" with a unique integer value (which I chose to use a random integer from a wide range). Now why Google didn't include this in their docs? Beats me...
Here's how my JSON looks now, when it creates separate notifications instead of overriding:
{
"data": {
"some_key":"some_val",
"title":"test title",
"message":"Test message from 30.09.2015 12:57:44",
"notId":14243
},
"registration_ids":["*******"]
}
Edit:
I'm now thinking that the notId parameter is not really determined by Google, but by a plugin I use on the mobile app side.
To extend further on my environment, my mobile app is developed using Phonegap, so to get push notification I use phonegap-plugin-push which I now see in its docs that parameter name.
I'm kinda' lost now as far as explaining the situation - but happy it is no longer a problem for me :-)
You need to pass a unique ID to each notification. Once you have clicked on the notification you use that ID to remove it.
...
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID_A);
...
But I'm sure you shouldn't have so much of notifications for user at once. You should show a single notification that consolidates info about group of events like for example Gmail client does. Use Notification.Builder for that purpose.
NotificationCompat.Builder b = new NotificationCompat.Builder(c);
b.setNumber(g_push.Counter)
.setLargeIcon(BitmapFactory.decodeResource(c.getResources(), R.drawable.list_avatar))
.setSmallIcon(R.drawable.ic_stat_example)
.setAutoCancel(true)
.setContentTitle(pushCount > 1 ? c.getString(R.string.stat_messages_title) + pushCount : title)
.setContentText(pushCount > 1 ? push.ProfileID : mess)
.setWhen(g_push.Timestamp)
.setContentIntent(PendingIntent.getActivity(c, 0, it, PendingIntent.FLAG_UPDATE_CURRENT))
.setDeleteIntent(PendingIntent.getBroadcast(c, 0, new Intent(ACTION_CLEAR_NOTIFICATION), PendingIntent.FLAG_CANCEL_CURRENT))
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
.setSound(Uri.parse(prefs.getString(
SharedPreferencesID.PREFERENCE_ID_PUSH_SOUND_URI,
"android.resource://ru.mail.mailapp/raw/new_message_bells")));
This is my situation. I have a chat-room website. People are publicly chatting together and everyone see who is writing what. All the chats are stored in database (mysql)
Now I want to implement this chatting on Android. So when user sends a text from his phone it should be sent to the chat-room website and vice versa, meaning the Android user should see all texts which are being sent from the chat webpage.
As a result:
1: Android user should see all the texts which people send via the webpage,
2: Android user should be able to send a text to this chat-room webpage (so other users which are using the webpage to chat should see his text).
The big question is, what is the best way to achieve this?
Could this process happen in real time like XMPP?
Is GCM the only way (although it is not real time)?
If i use web services to send the messages to the web, how can i set a listener for the incoming messages?
I don't know if i am clear. Any help is appreciated. Just give the head of the string i will go to the end...
Edit: a server side question: Is there anyway to make the server do something when a specific table in MYSQL is changed (for example when a new row is added)?
The first thing that leapt into my mind was that this fits fairly well into the Pub/Sub paradigm. Clients publish chat messages to specific channels (rooms,) and also subscribe to the channels; the server subscribes to a channel and stores the data in a MySQL database.
You might try using an external real-time network like PubNub. PubNub is free for up to 1m messages (see the pricing page.) They have an Android SDK and PHP SDK (I assume you're using PHP on your server due to your use of the PHP tag.)
In your case, in your Android client, you'd subscribe to a channel:
Pubnub pubnub = new Pubnub("demo", "demo");
try {
pubnub.subscribe("my_channel", new Callback() {
//See full example for all Callback methods
#Override
public void successCallback(String channel, Object message) {
System.out.println("SUBSCRIBE : " + channel + " : "
+ message.getClass() + " : " + message.toString());
}
}
} catch (PubnubException e) {
System.out.println(e.toString());
}
(Full example here.) Then, when you want to publish a message:
Callback callback = new Callback() {
public void successCallback(String channel, Object response) {
Log.d("PUBNUB",response.toString());
}
public void errorCallback(String channel, PubnubError error) {
Log.d("PUBNUB",error.toString());
}
};
pubnub.publish("my_channel", "This is an important chat message!" , callback);
Neat! But what about your server, how does it receive these messages?
$pubnub = new Pubnub(
"demo", ## PUBLISH_KEY
"demo", ## SUBSCRIBE_KEY
"", ## SECRET_KEY
false ## SSL_ON?
);
$pubnub->subscribe(array(
'channel' => 'my_channel', ## REQUIRED Channel to Listen
'callback' => function($message) { ## REQUIRED Callback With Response
## Time to log this to MySQL!
return true; ## Keep listening (return false to stop)
}
));
I hope this helps your project. Let me know how it goes.
SHORT ANSWER
Here's link to CODETUTS
and to a SAMPLE
LONG ANSWER
For make a chat in realtime compatible with android using db like mysql you have various way. the first who come up to me is to do some api but is not the most good way cause you will have to do many request to your server. So i advice you to use technology like nodeJs and socketIO (just google them...you will find tons of example), take a look to the link i've found for you. Have a nice day. Antonio
You need websockets on the web to do this in real time, in android you need to send push notifications.
Maybe you want to check "Google Cloud Messaging for Android".
This is an effort to develop a Android application which enable C2DM
Things I have done correctly
Get a valid Gmail address with C2DM
Write an Android app for getting a registrationId from C2DM
Get that registrationId from C2DM
Pass that registrationId to the third party server (I sent to a php
page) (1)
Send it correctly (I checked it with the HttpEntity class in the same
android app and I got the content of that page)
Getting Google authentication ID in server side (used PHP)
Open a Gmail account in my emulator (Menu - Settings - Accounts & sync - Add acount)
Things I am confused
How that web page (1) get notified when my Android app passed a "http" request?
How can I display the registrationId in the web page which sent by my Android app?
Things that wont work
Sending PushNotification to the emulator which runs my Android app. Referred this. That code is really good and first part also woks for me. But when I run the sendMessageToPhone() function it sends me 401. In my code I hard coded the values for;
$authCode = Google authentication code I get
$deviceRegistrationId = Code sent by the C2DM to my Android app
So please help me to clear my confusions and to correct my "wont work" activities.
Here is a simplest code for sending POST request to PHP:
String url = "http://your.domain.com/path/to/your/post/request/handler.php";
HttpClient client = new DefaultHttpClient();
try {
List<NameValuePair> post = new ArrayList<NameValuePair>();
post.add(new BasicNameValuePair("registrationId", "[YOUR ID VALUE HERE]"));
client.setEntity(new UrlEncodedFormEntity(post));
client.execute(new HttpPost(url));
} catch(IOException e) {
//do something here
}
On server side(i.e. in your PHP script) you can use $_POST superglobal variable which is populated from POST data and it's a simple associative array. Something like this:
if (!empty($_POST['registrationId'])) {
//do something here
}
I try to get the Live Delegated Authentication to work for the purpose of reading the email addresses.
I am doing this in PHP with the help of the windowslivelogin library. The problem is that I get an error.
I'm not sure what I'm doing wrong, i registered my application on the Azure webpage and got the appid and the secret into the code. This is what i use to initialize the Live Library :
$o = new WindowsLiveLogin();
$o->setAppId('000000004801B670');
$o->setSecret('secret');
$o->setSecurityAlgorithm('wsignin1.0');
$o->setDebug(true);
$o->setPolicyUrl('http://www.google.com/aides.html');
$o->setReturnUrl("http://michaelp.dev.gamepoint.net/framework/mainsite/contactimporter/?service=live");
return $o;
Then I call
$this->LiveLibrary->getLoginUrl()
And after I Login in to Live, it posts 2 things back, $_POST['stoken'] and $_POST['action'].
As soon as I call
$this->LiveLibrary->processLogin($_REQUEST);
It fails and gives back an error that the token is invalid.
I tried getting Consent straight away by making redirecting to
$this->LiveLibrary->getConsentUrl("Contacts.View");
But that gives an 3007 error and says that it cant share the information
According to MS this means the following :
3007
Consent Service API failed in the <method name> method. The application verifier is invalid.
The offer security level requires that a valid application verifier be passed with the request.
I am using the following URL, generated by the library
https://consent.live.com/Delegation.aspx?ps=Contacts.Invite&ru=http%3A%2F%2Fmichaelp.dev.gamepoint.net%2Fframework%2Fmainsite%2Fcontactimporter%2F%3Fservice%3Dlive&pl=http%3A%2F%2Fwww.google.com%2Faides.html&app=appid%3D000000004801B670%26ts%3D1251722931%26sig%3DD2gkM%252F%252FwlRXXfS64NMrV%252Bkt50v6dAOcESblfRk7j%252FUE%253D
I don't understand most of the documentation Microsoft has on this thing, I think its really unclear and chaotic. Also the Sample I tried doesn't work. I get an error message, it can't validate/decode the token. Same I get when I try the processLogin().
Thanks in Advance,
Michael