I need to implement c2dm in my app. Is there anyone who is also doing this? Please help..some tutorials will be very he开发者_如何学Clpful OR if you have completed your c2dm implementation then a tutorial is more than appreciated.
Please help.
I went ahead and downloaded the Chrome2Phone source code for android and understood how it works through that example, I had the most trouble implementing the server side of the App.
Download it from: http://code.google.com/p/chrometophone/source/checkout
or svn it:
svn checkout http://chrometophone.googlecode.com/svn/trunk/ chrometophone-read-only
Basic things you should understand.
In the C2DMBaseReciever class you have:
@Override
public final void onHandleIntent(Intent intent) {
try {
Context context = getApplicationContext();
if (intent.getAction().equals(REGISTRATION_CALLBACK_INTENT)) {
handleRegistration(context, intent);
} else if (intent.getAction().equals(C2DM_INTENT)) {
onMessage(context, intent);
} else if (intent.getAction().equals(C2DM_RETRY)) {
C2DMessaging.register(context, senderId);
}
} finally {
// Release the power lock, so phone can get back to sleep.
// The lock is reference counted by default, so multiple
// messages are ok.
// If the onMessage() needs to spawn a thread or do something else,
// it should use it's own lock.
mWakeLock.release();
}
}
This method recieves the intents from the C2DM service and handles them.
In the handleRegistration method you will see some code that looks like:
} else {
try {
onRegistrered(context, registrationId);
C2DMessaging.setRegistrationId(context, registrationId);
//Add some code here to send your server the registration ID for this phone.
} catch (IOException ex) {
Log.e(TAG, "Registration error " + ex.getMessage());
}
}
You then have to use the google oAuth login service to register your server to the service, once that is done you can send a message. When I was testing I was using curl to send http post requests to the server.
To register from the server:
curl https://www.google.com/accounts/ClientLogin -d Email=theEmailYouWhitelisted -d Passwd=pass****word -d accountType=HOSTED_OR_GOOGLE -d source=Google-cURL-Example -d service=ac2dm
You will get a message with an auth id. You then use that to send the messages. To send a message use:
curl --header "Authorization: GoogleLogin auth=**authFromRegistrationAbove**" "https://android.apis.google.com/c2dm/send" -d registration_id=**phoneRegistrationId(reciever)** -d "data.message=StringToPass" -d collapse_key=something -k
Download curl from: CURL
Hope this helps.
a tutorial about c2dm client/server registration and sending/receiving of messages.
http://android.arnodenhond.com/tutorials/cloud-to-device-messaging
- intent to request a registration id
- receiver to receive registration id
- url to call for registering the server
- url to call for sending a message
- broadcast receiver to receive the message
精彩评论