GCM Service for android shows java.net.UnknownHostException: android.googleapis.com - android

Code for the GCMService:
package com.avilyne.gcm;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Sender;
/**
* Servlet implementation class GCMBroadcast
*/
#WebServlet("/GCMBroadcast")
public class GCMBroadcast extends HttpServlet {
private static final long serialVersionUID = 1L;
// The SENDER_ID here is the "Browser Key" that was generated when I
// created the API keys for my Google APIs project.
private static final String SENDER_ID = "AIzaSyCOLAYwS2P3ELqnTiPs3VPHGquQy1UoEIQ";
// This is a *cheat* It is a hard-coded registration ID from an Android device
// that registered itself with GCM using the same project id shown above.
private static final String ANDROID_DEVICE = "APA91bEF-_Y7t3Vc59OGuK9gnBWDegE4g2KyVgNeVIZbjGWe-4b9FMHrL82oOEYRPVz7_GaCOHbq3PatsuU_pk8jhvGng3Xp-CAv48iPqamer8Y2aajyTvUho9hsy39uNudA8XI4ML09eUsPNH87zcuGc_v2uJj65g";
// This array will hold all the registration ids used to broadcast a message.
// for this demo, it will only have the ANDROID_DEVICE id that was captured
// when we ran the Android client app through Eclipse.
private List<String> androidTargets = new ArrayList<String>();
/**
* #see HttpServlet#HttpServlet()
*/
public GCMBroadcast() {
super();
// we'll only add the hard-coded *cheat* target device registration id
// for this demo.
androidTargets.add(ANDROID_DEVICE);
}
// This doPost() method is called from the form in our index.jsp file.
// It will broadcast the passed "Message" value.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// We'll collect the "CollapseKey" and "Message" values from our JSP page
String collapseKey = "";
String userMessage = "";
try {
userMessage = request.getParameter("Message");
collapseKey = request.getParameter("CollapseKey");
} catch (Exception e) {
e.printStackTrace();
return;
}
// Instance of com.android.gcm.server.Sender, that does the
// transmission of a Message to the Google Cloud Messaging service.
Sender sender = new Sender(SENDER_ID);
// This Message object will hold the data that is being transmitted
// to the Android client devices. For this demo, it is a simple text
// string, but could certainly be a JSON object.
Message message = new Message.Builder()
// If multiple messages are sent using the same .collapseKey()
// the android target device, if it was offline during earlier message
// transmissions, will only receive the latest message for that key when
// it goes back on-line.
.collapseKey(collapseKey)
.timeToLive(30)
.delayWhileIdle(true)
.addData("message", userMessage)
.build();
try {
// use this for multicast messages. The second parameter
// of sender.send() will need to be an array of register ids.
MulticastResult result = sender.send(message, androidTargets, 1);
if (result.getResults() != null) {
int canonicalRegId = result.getCanonicalIds();
if (canonicalRegId != 0) {
}
} else {
int error = result.getFailure();
System.out.println("Broadcast failure: " + error);
}
} catch (Exception e) {
e.printStackTrace();
}
// We'll pass the CollapseKey and Message values back to index.jsp, only so
// we can display it in our form again.
request.setAttribute("CollapseKey", collapseKey);
request.setAttribute("Message", userMessage);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
Since it is a web service, it does not have android_manifest.xml. So permission for internet cannot be added.
If I want to change the host(android.googleapis.com), then how should I do it. (it seems broken).

Have you tried to turn off your firewall? You have to enable gcm ports.
If your organization has a firewall that restricts the traffic to or
from the Internet, you need to configure it to allow connectivity with
GCM. The ports to open are: 5228, 5229, and 5230. GCM typically only
uses 5228, but it sometimes uses 5229 and 5230. GCM doesn't provide
specific IPs, so you should allow your server to accept incoming
connections from all IP addresses contained in the IP blocks listed in
Google's ASN of 15169.
BTW GCM message request is a simple http post, without Message Builder you have to post a message in json format.
Android developer site
More information about message fields

Related

Grails Firebase Cloud Messaging Plugin

I'm looking to port an application server sending downstream Android GCM notifications over to Firebase Cloud Messaging. I'm currently using the Android GCM plugin for Grails to send downstream messages.
https://grails.org/plugin/android-gcm
I don't see a Grails FCM plugin to send downstream messages. I'm I missing something or does it not yet exist?
I decided to move forward by issuing a Http request directly from Grails. I don't have enough reputation to post more than 2 links, so I wrapped them in code samples, sorry. Per
https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream
Errors in the 500-599 range (such as 500 or 503) indicate that there
was an internal error in the FCM connection server while trying to
process the request, or that the server is temporarily unavailable
(for example, because of timeouts). Sender must retry later, honoring
any Retry-After header included in the response. Application servers
must implement exponential back-off.
so I decided to use Google's Http Java Client which provides exponential back-off
https://developers.google.com/api-client-library/java/google-http-java-client/
https://developers.google.com/api-client-library/java/google-http-java-client/backoff
For a use case example add the dependencies:
compile 'com.google.http-client:google-http-client:1.22.0'
compile 'com.google.http-client:google-http-client-jackson2:1.22.0'
Then implement a simple controller using the HTTP Post Request example
https://firebase.google.com/docs/cloud-messaging/downstream
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler
import com.google.api.client.http.HttpTransport
import com.google.api.client.http.HttpRequest
import com.google.api.client.http.HttpResponse
import com.google.api.client.http.GenericUrl
import com.google.api.client.http.HttpUnsuccessfulResponseHandler;
import com.google.api.client.http.json.JsonHttpContent
import com.google.api.client.json.jackson2.JacksonFactory
import com.google.api.client.util.ExponentialBackOff
import com.google.api.client.http.HttpHeaders
import com.google.api.client.http.HttpResponseException
class MyPushController {
def push(String token){
def postJson = [:]
def data = [:]
data['score'] = '5x1'
data['time'] = '15:10'
postJson['data'] = data
postJson['to'] = token
log.info "postJson: ${postJson}"
HttpTransport transport = new NetHttpTransport()
HttpRequest request = transport.createRequestFactory().buildPostRequest(new GenericUrl("https://fcm.googleapis.com/fcm/send"), new JsonHttpContent(new JacksonFactory(), postJson));
HttpHeaders reqHeaders = new HttpHeaders()
reqHeaders.setAuthorization("key=${grailsApplication.config.android.fcm.api.key}")
reqHeaders.setAccept("application/json")
reqHeaders.setContentType("application/json")
request.setHeaders(reqHeaders)
request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff.Builder()
.setInitialIntervalMillis(500)
.setMaxElapsedTimeMillis(900000)
.setMaxIntervalMillis(6000)
.setMultiplier(1.5)
.setRandomizationFactor(0.5)
.build()
))
try{
HttpResponse response = request.execute();
InputStream is = response.getContent()
BufferedReader br = new BufferedReader(new InputStreamReader(is))
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
ObjectMapper mapper = new ObjectMapper()
Map<String, Object> responseMap = mapper.readValue(sb.toString(), new TypeReference<Map<String, Object>>(){})
// Process response JSON per https://firebase.google.com/docs/cloud-messaging/server#response
if(responseMap && (responseMap['failure'] != 0 || responseMap['canonical_ids'] != 0)){
if(responseMap['message_id'] && responseMap['registration_id']){
log.info "New push token, setting to ${responseMap['registration_id']}"
// TODO Notify backend that token has changed, i.e. update
}
}else{
def results = responseMap['results']
if(results){
results.each{
if(it['error']){
if(it['error'] == "NotRegistered"){
log.info 'NotRegistered, updating AppToken to null'
// TODO Notify backend this token is no longer valid, i.e. delete
}
}
}
}
}
}
render responseMap as JSON
}catch(HttpResponseException e){
log.error "Error: ${e.toString()}"
render (['SC' : e.getStatusCode(), 'M' : e.getStatusMessage() ]) as JSON
}
}
}
Be sure to replace ${grailsApplication.config.android.fcm.api.key} with your FCM Server Key. Your FCM Server Key can be found by logging into the Firebase console:
https://console.firebase.google.com
Then go to Project Settings -> CLOUD MESSAGING

Firebase 401 unauthorized error FCM

I'm trying to test out Firebase Cloud messaging APIs as all functionality is not available from console (notably customization of notifications when app is in background). But for some reasons, I cannot get it to work, and it always shows up 401 error. I investigated the reasons for this, and tried it after regenerating new server key, but the error remains constant. Surprisingly, when I generated a new server key, it is not reflected in Firebase console and it shows server key as empty. Also, I tried adding my IP address to the server whitelist IPs but still no luck. I've attached a screenshot of a request that I did with Postman (I substitue the server key in place of serverKey.
I'm stuck on this for a few hours and would really appreciate some help.
I don't know if someone uses the [Web API Key] as the [YOUR_SERVER_KEY] for POSTMAN test and keep getting '401 Error'. [Web API Key] is not [YOUR_SERVER_KEY].
You should go to your Firebase console and check this:
to get the correct Server key.
Hope it help.
I noticed from your screenshot that you were using "key: serverKey". Could you try using "key=serverKey" instead?
Also you don't need to have "POST fcm.googleapus.com/fcm/send"; this is not proper json and would explain the error you are seeing. The URL of the request is already defined elsewhere so remove it from the payload.
I faced the same problem.
the problem was that I was using the legacy server key. when I used the new version of the server key the problem solved.
in your firebase console goto settings -> cloud messaging
then use the new server key. it is longer than the old version key.
go to https://console.firebase.google.com/u/0/project/[project-name]/settings/cloudmessaging/
you can use Server Key or Legacy server key
I too am facing the Same problem... I am using curl in php for posting and it works only if I have php files stored on my LocalHost server. When I try to use access the files via a free hosting online, then it say Unautorized 401.
So I would suggest if you can, use the Localhost.
I have the same problem at Server Side Code(C#).
You basically used wrong Server Key (or API Key) for service side code.
Follow below Link over stackoverflow posted by me (Helpful to find Server Key (or API Key) )
FCM (Firebase Cloud Messaging) Push Notification with Asp.Net
401 with FCM through HTTPv1 (Error and Solution for Bearer)
If you are using FCM via HTTP v1, then you will have to make two sucessive POST requests:
1/ In the first call, you make a POST request to 'https://accounts.google.com/o/oauth2/token' (or using API packages) using your firebase service account key at
'https://console.firebase.google.com/u/0/project/{{firebaseProjectName}}/settings/serviceaccounts/adminsdk'
to get the access token.
2/ Then you have to make another POST request to 'https://fcm.googleapis.com/v1/projects/{{firebaseProjectName}}/messages:send'. If you have followed the steps for the migration from legacy HTTP to HTTP v1 (very clear documentation) on firebase website, you have to make some small changes at the content of the post request and also using 'Bearer ${accessToken.data}' for the Authorization.
In my case I was not properly awaiting for the accessToken in the first function (forgot the 'await' keyword in front of the function making the post request and AndroidStudio did not notice either that there was something wrong).
Make sure that you await the result of the first post request as it is a Future.
If you don't, Bearer will be null when you make the second POST request because you did not await for it.
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.Size;
public class PushNotificationSubmit {
public static void main(String[] args) {
new PushNotificationSubmit().send("sample message title", "sample message body");
}
final String serverKey = "AAAA_*******";
final String fcmUrl = "https://fcm.googleapis.com/fcm/send";
/**
* note from google: The value should be an array of registration tokens to which to send the multicast message. The array must contain at least 1 and at most 1000 registration tokens.
* send to specific users
*
* #param messageTitle
* #param messageBody
* #param tokenList
*/
#Size.List({#Size(min = 1), #Size(max = 999)})
public void send(String messageTitle, String messageBody, List<String> tokenList) {
try {
String payloadJson = createMessageAsJson(messageTitle, messageBody, tokenList);
doSend(payloadJson);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* send to all users that registered in my topic
*
* #param messageTitle
* #param messageBody
*/
public void send(String messageTitle, String messageBody) {
try {
String payloadJson = createMessageAsJson(messageTitle, messageBody, null);
doSend(payloadJson);
} catch (Exception e) {
e.printStackTrace();
}
}
private String createMessageAsJson(String messageTitle, String messageBody, List<String> tokenList) {
JSONObject payloadObj = new JSONObject();
try {
JSONObject notifyObj = new JSONObject();
notifyObj.put("title", messageTitle);
notifyObj.put("body", messageBody);
payloadObj.put("notification", notifyObj);
if (tokenList != null) {
if (tokenList != null && tokenList.size() > 0) {
JSONArray regId = new JSONArray();
for (int i = 0; i < tokenList.size(); i++) {
regId.put(tokenList.get(i));
}
payloadObj.put("registration_ids", regId);
}
} else {
payloadObj.put("to", "/topics/all");
}
return payloadObj.toString();
} catch (Exception e) {
// TODO: add logger
e.printStackTrace();
throw e;
}
}
private void doSend(String payloadJson) throws Exception {
HttpClient httpclient = HttpClientBuilder.create().build();
try {
HttpPost httpPost = new HttpPost(fcmUrl);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "key=" + serverKey);
httpPost.setEntity(new StringEntity(payloadJson, "UTF-8"));
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println("push notification status: " + response.getStatusLine());
EntityUtils.consume(entity);
} finally {
httpclient.getConnectionManager().shutdown();
}
}
}
In C# HttpClient response
For wrong server key it will happen, Invalid Key, Unauthorize, 401
I was facing the same problem, i solved it by using the following steps
1- In the server from where you are sending push, Use the browser key only, you can get it from Firebase console or google api console as I have highlighted in the below images:-
Google api console
Firebase console, click on the project-->settings
Note : The Firebase console web api key and google console browser key are the same you can use either of them
2- If you follow the first step only you will get the Unauthorized error, to resolve this you need to authorize your browser key in google console by adding your server IP address from where you will send the push. Click on the edit pencil icon on the right side of your browser key in google api console, above first image
After adding your Ip address click save
Make sure that your device token is not empty on which you are sending the push, I hope your push will be sent successfully now.

How to send message to notification key with GCM without an app server

I followed Google Cloud Messaging (GCM) with local device groups on Android gives HTTP Error code 401 to manage local device groups on Android and successfully got a notification key, but when I send message to the notification key, I never get the message back.
Has anyone ever got this work?
My send code is like:
public void sendMessage(View view) {
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
try {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
String to = notificationKey; // the notification key
AtomicInteger msgId = new AtomicInteger();
String id = Integer.toString(msgId.incrementAndGet());
Bundle data = new Bundle();
data.putString("hello", "world");
gcm.send(to, id, data);
Log.e(TAG, "sendMessage done.");
} catch (Exception ex) {
Log.e(TAG, ex.toString());
}
return null;
}
};
task.execute();
}
It seems there's a misunderstanding about the GCM concept. The app server is an integral part of GCM messaging.
The server side of Google Cloud Messaging (GCM) consists of two
components:
GCM connection servers provided by Google. These servers take messages
from an app server and send them to a client app running on a device.
Google provides connection servers for HTTP and XMPP.
An application
server that you must implement in your environment. This application
server sends data to a client app via the chosen GCM connection
server, using the appropriate XMPP or HTTP protocol.
Try the Android GCM Playground to get a better understanding of this.
Here's a snippet:
public void sendMessage() {
String senderId = getString(R.string.gcm_defaultSenderId);
if (!("".equals(senderId))) {
String text = upstreamMessageField.getText().toString();
if (text == "") {
showToast("Please enter a message to send");
return;
}
// Create the bundle for sending the message.
Bundle message = new Bundle();
message.putString(RegistrationConstants.ACTION, RegistrationConstants.UPSTREAM_MESSAGE);
message.putString(RegistrationConstants.EXTRA_KEY_MESSAGE, text);
try {
gcm.send(GcmPlaygroundUtil.getServerUrl(senderId),
String.valueOf(System.currentTimeMillis()), message);
showToast("Message sent successfully");
} catch (IOException e) {
Log.e(TAG, "Message failed", e);
showToast("Upstream FAILED");
}
}
}
The to field of the send method represents the sender ID of your project. You cannot use this method to send messages to Instance ID tokens (other devices), Device to Device messaging is not currently supported by GCM.
You are correct to avoid including the API key in your client app, so currently you will need an app server to send these types of messages.

Google App Engine backend with Google Cloud Messaging

I'm trying out a GAE based backend using the sample code on the page below:
https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/GcmEndpoints
Have been able to deploy the backend and I can view & execute the APIs on API explorer through appspot.com link - project-id.appspot.com
When I execute the client app (Android based) and call
regService.register(regId).execute();
On the server side I get the following log entry on Google Developer Console -
"POST /registration/v1/registerDevice/APA91bHCCvjkMFdvf6YHh_rbdqdKMYoRnwm6iswQtTpztwCfNVWq_7xwSq1y9naiipYmfTrREInybypeLb5mc7LCzYGBSpC9jFM-Co_6xGUBiEjLyo1UT375ak7p0nrOiTdHFNwW7r31WYQJP7ojigRLxBTYvST4XTeNIufD6GHb3SbDFGl1hsc HTTP/1.1" 404 0 - "20773xxxxxxx Google-HTTP-Java-Client/1.17.0-rc (gzip)" "verlllll-auyyyy-zzz.appspot.com" ms=19 cpu_ms=0 app_engine_release=1.9.7 trace_id=ddfbcf4e13e27e2aa2a6c5e77bb8cc6f
where:
registration/v1/registerDevice/ are API/version/Method of the backend service
APA91bHCCvjkMFdvf6YHh_rbdqdKMYoRnwm6iswQtTpztwCfNVWq_7xwSq1y9naiipYmfTrREInybypeLb5mc7LCzYGBSpC9jFM-Co_6xGUBiEjLyo1UT375ak7p0nrOiTdHFNwW7r31WYQJP7ojigRLxBTYvST4XTeNIufD6GHb3SbDFGl1hsc
.. is the device registration id returned by gcm.register(SENDER_ID); gcm is of type GoogleCloudMessaging
20773xxxxxxx or SENDER_ID is the Project number provided on the Google Developer Console.
& verlllll-auyyyy-zzz.appspot.com is the Project Id.
Can you please tell me why am I getting HTTP/1.1 404 in the response?
Thanks in advance..
Sharing the building of regService --
public class GcmRegistrationAsync extends AsyncTask<Context, Void, String> {
private Registration regService; // A Stub API from Server
private GoogleCloudMessaging gcm;
private Context context;
// TODO: change to your own sender ID to Google Developers Console project
// number, as per instructions above
private static final String SENDER_ID = "20773xxxxxxx";
public void GcmRegistrationAsyncTask(int i) {
Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
// Need setRootUrl and setGoogleClientRequestInitializer only for local testing,
// otherwise they can be skipped
.setRootUrl("https://verlllll-auyyyy-zzz.appspot.com")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
i = this.test();
builder.setApplicationName(SENDER_ID);
regService = builder.build();
}
public int test () {
return 1;
}
#Override
protected String doInBackground(Context... params) {
int i = params.length;
context = (Context) params[0];
String msg = "test";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
String regId = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regId;
// You should send the registration ID to your server over HTTP,
// so it can use GCM/HTTP or CCS to send messages to your app.
// The request to your server should be authenticated if your app
// is using accounts.
regService.register(regId).execute();
} catch (IOException ex) {
ex.printStackTrace();
msg = "Error: " + ex.getMessage();
}
return msg;
}
}
In MyActivity.java
protected void onCreate(Bundle savedInstanceState) {
:
:
gcmRegistrationAsync = new GcmRegistrationAsync();
gcmRegistrationAsync.GcmRegistrationAsyncTask(1);
gcmRegistrationAsync.execute(this);
}
To connect to an endpoint you have to connect with https, if you connect with http like you did (in your setUrl) then you get the 404 error.
Also your code can probably look more like :
Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null);
The rootUrl doesn't need be set, by default it uses your appspot location, when running locally, it's useful to direct the endpoint to your devapp server (app engine local testing server).
The code that disables compression is also just used to be compatible with the devapp server

How to create server for GCM project in Android

I am creating a project on Google Cloud Messaging (GCM) and am following this tutorial.
I am done with the client-side work and set up the device on the client side. Also I had registered the device using the following code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, "483910217912");
Log.d(tag, "Registered");
}
else {
Log.v(tag, "Already registered");
}
}
Now I am stuck at a point to create server for my GCM project. Note that I am creating a project to notify when a new message is received. However, I had not implemented the service to receive a message, but I will implement it when the server setting is finished.
You can create a GCM server in Android using the blog post Google cloud Messaging (GCM) tutorial , but I would prefer to use PHP for server side code. You can create a GCM Server in cURL (PHP) in easy steps:
Create a server key from the Google API console page.
Identify the device token of a device for which this message is sent to.
You can find the easy steps in How to implement a GCM PHP push server for Android to implement the push server.
you can use this code
package yourpackage.android.gcm.server;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Sender;
import java.util.ArrayList;
class Notify {
public static void main(String args[]) {
try {
Sender sender = new Sender("AIzaSyCn3N2OIm-EDtiGwTyQfSIB8NRvDtIOx30");
ArrayList<String> devicesList = new ArrayList<String>();
//add you deviceID
devicesList.add("APA91bELVJbxB_NLnLbTkkkX87SDdkJc6OfCN2slhC9t4cLq-KA32eGgiW4-Gi--ZEsEMKIh0AtYJMs5rQGswfm3cH1qK853WcpV98bkaplAaC5AiycDmifuVFSRl21vgf-Rqj0dCrFF");
//devicesList.add("APA91bHIdM4XGqrjJLTuwCX5OOrTYG4ACXYEVkZDM1bPs5qFdzJP4Bpql-sZqyKB8BU7fDtdxB84aTygHLyASYg_XNY6lqrcA4wj4sZHJXGVFzz_0UEADMfFCx9NAfRZxunIYso_dkBa");
//APA91bFA-i2l3iEMnIBs0JK80pTLHOsE7p1s-DysRpKGas1MQOVILyIs9xwY7soysSWGz5Uif68uXR6F5Xn0tCTYesv78uQZxhC310a1cvf8aFohhfMGY6awbOSg3t1GRz2i3U-8kVSF
// Use this line to send message without payload data
// Message message = new Message.Builder().build();
// use this line to send message with payload data
Message message = new Message.Builder()
//.collapseKey("message")
//.timeToLive(241000)
.delayWhileIdle(true)
.addData("message", "Your message send")
.build();
/**/
// Use this code to send to a single device
// Result result = sender
// .send(message,
// "APA91bGiRaramjyohc2lKjAgFGpzBwtEmI8tJC30O89C2b3IjP1CuMeU1h9LMjKhmWuZwcXZjy1eqC4cE0tWBNt61Kx_SuMF6awzIt8WNq_4AfwflaVPHQ0wYHG_UX3snjp_U-5kJkmysdRlN6T8xChB1n3DtIq98w",
// 1);
// Use this for multicast messages
MulticastResult result = sender.send(message, devicesList, 1);
//sender.send(message, devicesList, 0);
System.out.println(result.toString());
if (result.getResults() != null) {
int canonicalRegId = result.getCanonicalIds();
if (canonicalRegId != 0) {
}
} else {
int error = result.getFailure();
System.out.println(error);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The com.google.android.gcm.server library is deprecated. Just encode your message to JSON object and POST it to GCM URL https://android.googleapis.com/gcm/send
JSON example:
{
"registration_ids" : ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",...],
"data" : {
"Team" : "Portugal",
"Score" : "3",
"Player" : "Varela",
},
}
Here is more http://developer.android.com/google/gcm/http.html
You can find sample code for gcm-client and gcm-server in the Android SDK directory. It is good point to get started. Directory is :
path_to_android_sdk/extras/google/gcm/samples
In your main function implement following code to send push notification to your app
final String apiKey = "specify your api key generated by gcm";
To make http connection to gcm using following code
URL url = new URL("https://android.googleapis.com/g...");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+apiKey);
conn.setDoOutput(true);
JSON message format accepted by GCM
String input = "{\"registration_ids\" : [\"Specify token you got from GCM\"],\"data\" : {\"message\": \"hai welcome\"},}";
To send notification
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
In your client app you need to have proper BroadcastReceiver class to receive the message sent from GCM
I would insist you to test the demo that is being provided on the develpers site. I had just created a demo sample based on that with all the steps that one should follow for executing the demo sample. You can check my blog and also find the source from my github.

Categories

Resources