Skip to content

Instantly share code, notes, and snippets.

@Ahmedbadereldin
Last active August 6, 2019 08:57
Show Gist options
  • Save Ahmedbadereldin/df0f5761e1025a234d8d3f4f6b6502f3 to your computer and use it in GitHub Desktop.
Save Ahmedbadereldin/df0f5761e1025a234d8d3f4f6b6502f3 to your computer and use it in GitHub Desktop.
Working easily with FCM push notifications in Android ,
final private String FCM_API = "https://fcm.googleapis.com/fcm/send";
//server Key => get From Your Firbase account
final private String serverKey = "key=" + "AAAA.......";
final private String contentType = "application/json";
final String TAG = "NOTIFICATION TAG";
------------------------------------------------------------------------------------
newMessageDoc.set(newChatMessage).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
// topic when user login , using this code in the response
//FirebaseMessaging.getInstance().subscribeToTopic("user_" + user.getId());
TOPIC = "/topics/user_" + userRecever.getId(); //topic has to match what the receiver subscribed to
NOTIFICATION_TITLE = "Ahmed M Bader El-Din"; // title notification
// in this example title my name
NOTIFICATION_MESSAGE = "Hi How Are You!!!";
JSONObject notification = new JSONObject();
JSONObject notifcationBody = new JSONObject();
try {
notifcationBody.put("title", NOTIFICATION_TITLE);
notifcationBody.put("chatID", id_chat);// using this becuse when the user revice message , when click notify can you open the chat directly (^_^)
notifcationBody.put("body", NOTIFICATION_MESSAGE);
Log.i("sendMessage", "sendMessage: " + TOPIC + " " + notifcationBody);
notification.put("to", TOPIC);//send this notifi to user_topic // e.g user_1234
notification.put("notification", notifcationBody); // notification
notification.put("data", notifcationBody);//data for notification
} catch (JSONException e) {
Log.e(TAG, "onCreate: " + e.getMessage());
}
sendNotification(notification);
} else {
View parentLayout = findViewById(android.R.id.content);
Snackbar.make(parentLayout, "Something went wrong.", Snackbar.LENGTH_SHORT).show();
}
});
------------------------------------------------------------------------------------
private void sendNotification(JSONObject notification) {
//FCM_API => URL
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(FCM_API, notification,
response -> {
Log.i("onResponse", "onResponse: " + response.toString());
},
error -> {
Toast.makeText(MessageActivity.this, "Request error", Toast.LENGTH_LONG).show();
Log.i("onErrorResponse", "onErrorResponse: Didn't work");
}) {
@Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("Authorization", serverKey);
params.put("Content-Type", contentType);
return params;
}
};
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment