-
Notifications
You must be signed in to change notification settings - Fork 30
/
AndroidPush.java
51 lines (43 loc) · 1.71 KB
/
AndroidPush.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class AndroidPush {
/**
* Replace SERVER_KEY with your SERVER_KEY generated from FCM
* Replace DEVICE_TOKEN with your DEVICE_TOKEN
*/
private static String SERVER_KEY = "YOUR_SERVER_KEY";
private static String DEVICE_TOKEN = "YOUR_DEVICE_TOKEN";
/**
* USE THIS METHOD to send push notification
*/
public static void main(String[] args) throws Exception {
String title = "My First Notification";
String message = "Hello, I'm push notification";
sendPushNotification(title, message);
}
/**
* Sends notification to mobile, YOU DON'T NEED TO UNDERSTAND THIS METHOD
*/
private static void sendPushNotification(String title, String message) throws Exception {
String pushMessage = "{\"data\":{\"title\":\"" +
title +
"\",\"message\":\"" +
message +
"\"},\"to\":\"" +
DEVICE_TOKEN +
"\"}";
// Create connection to send FCM Message request.
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// Send FCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(pushMessage.getBytes());
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
}
}