Last active
October 13, 2019 10:10
-
-
Save anta40/7befc95e7a577fd51b022bc9419137a5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.io.OutputStreamWriter; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
import org.json.JSONException; | |
import org.json.JSONObject; | |
public class FCMHelper { | |
private final static String AUTH_KEY_FCM = "xxxxxx" // Provide your FCM key here; | |
private final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send"; | |
public static String sendPushNotification(String deviceToken, String notificationTitle, String messageBody) throws IOException, JSONException { | |
String result = ""; | |
URL url = new URL(API_URL_FCM); | |
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); | |
conn.setUseCaches(false); | |
conn.setDoInput(true); | |
conn.setDoOutput(true); | |
conn.setRequestMethod("POST"); | |
conn.setRequestProperty("Authorization", "key=" + AUTH_KEY_FCM); | |
conn.setRequestProperty("Content-Type", "application/json"); | |
JSONObject json = new JSONObject(); | |
json.put("to", deviceToken.trim()); | |
JSONObject oData = new JSONObject(); | |
JSONObject oNotif = new JSONObject(); | |
oNotif.put("title", notificationTitle); | |
oNotif.put("body", messageBody); | |
oData.put("data1", "AAAA"); | |
oData.put("data2", "BBBBB"); | |
oData.put("data3", "CCC"); | |
json.put("notification", oNotif); | |
json.put("data", oData); | |
try { | |
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); | |
wr.write(json.toString()); | |
wr.flush(); | |
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); | |
String output; | |
System.out.println("Output from server: \n"); | |
while ((output = br.readLine()) != null) { | |
System.out.println(output); | |
} | |
result = "OK"; | |
} | |
catch (Exception e) { | |
e.printStackTrace(); | |
result = "BAD"; | |
} | |
System.out.println("GCM Notification is sent successfully"); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment