When I send a gcm message with useful information with a notification (no data), an Android notification is only displayed if my application is in the background. If the application is in the foreground, an Android notification is not displayed, but the onMessageReceived () function in the GcmListenerService is called with a null "message".
onMessageReceived () is not called when the application is in the background, and an Android notification is displayed as expected.
Is this the expected behavior or am I missing something? Please let me know if any client-side code is required.
Here is the server side code snippet:
Message.Builder messageBuilder = new Message.Builder();
messageBuilder.notification(new Notification.Builder("ic_launcher")
.clickAction("ScrHome1")
.title("Bling")
.body(blingNotification.getPayload().getValue())
.build());
Message message = messageBuilder.build();
sender.send(message, targetIdList, retries);
UPDATE
, b google, , . ?
gcm, , .
public class GcmSender {
public static final String API_KEY = "AIaSyCMzWOageHbcX9yxNtfL6RygdbLT-7Ls";
@SuppressWarnings("unchecked")
public static void main(String[] args) {
try {
JSONObject jGcmData = new JSONObject();
JSONObject jData = new JSONObject();
JSONObject jNotification = new JSONObject();
jData.put("message", "hello");
jNotification.put("body", "hi dev");
jNotification.put("title", "POC");
jNotification.put("icon", "ic_launcher");
jGcmData.put("to",
"eucb9MGv3g:APA91bGJWZjBET12nYuDrX8yiylPqt3uy87ThP2f4E9Nw89GOvbZkWSTFVPyQ8keTPQubWzpW_10-Aydqu04MD1GvzeTUAh6SoFk6qeXSUW0205h6sbQdTe74VZfMu8t2P9nrWOE");
jGcmData.put("notification", jNotification);
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "key=" + API_KEY);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream outputStream = conn.getOutputStream();
outputStream.write(jGcmData.toString().getBytes());
InputStream inputStream = conn.getInputStream();
String resp = IOUtils.toString(inputStream);
System.out.println(resp);
System.out.println("Check your device/emulator for notification or logcat for "
+ "confirmation of the receipt of the GCM message.");
} catch (IOException e) {
System.out.println("Unable to send GCM message.");
System.out.println("Please ensure that API_KEY has been replaced by the server "
+ "API key, and that the device registration token is correct (if specified).");
e.printStackTrace();
}
}
}
, , , , , , , MyGcmListenerService.onMessageReceived(String from, Bundle data) : From: 234552842207 : null.
, , .
, 3 .
, .