我正在尝试创建一个小型应用程序,该应用程序将读取计算机/笔记本电脑的CPU负载,并向我的主笔记本电脑的浏览器发送推送通知,该通知将包含用户名和处理器的加载量。作为一种发送通知的技术,我选择了FCM。代码本身已经准备好,但是我缺少一个细节。我需要获取此推送通知将发送到的便携式计算机的设备令牌(因为据我所知,设备令牌是将通知发送到的计算机的令牌)。但我不知道如何获得此令牌。大多数指南都针对Android,我需要将其从计算机发送到计算机。也许有人可以告诉我另一种发送这些通知的方法,或者我附加的选项也适合初学者?如果是这样,我如何获得此令牌?
public class MetricTesting {
Process p = Runtime.getRuntime().exec("typeperf \"\\238(_Total)\\6\"");
BufferedReader br = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String line;
double pr = 0;
Pattern pattern = Pattern.compile("[\\d]{0,3}\\.\\d{4,}");
while ((line = br.readLine()) != null) {
System.out.println(line);
Matcher m = pattern.matcher(line);
if (!m.find()) {
continue;
}
line = m.group();
pr = Math.round(Double.parseDouble(line) * 10.0) / 10.0;
System.out.println(pr);
if (pr > 5) {
PushNotificationSender.sendPushNotification("??", Double.toString(pr));
System.out.println(System.getProperty("user.name") + ", Processor loaded " + pr + " %");
}
}
String[] g = br.readLine().split("");
System.out.println(Arrays.toString(g));
br.close();
}
}
class PushNotificationSender {
public final static String AUTH_KEY_FCM = "//";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
public static String sendPushNotification(String deviceToken, String pr)
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 info = new JSONObject();
info.put("title", "CPU is overloaded");
info.put("body", System.getProperty("user.name")+"\n"+pr);
json.put("notification", info);
try {
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
result = "OK";
} catch (Exception e) {
e.printStackTrace();
result = "BAD";
}
return result;
}
}
答案 0 :(得分:0)
您必须尝试https://firebase.google.com/docs/cloud-messaging/js/client创建用于Firebase推送通知的Web客户端。 在以上文章中,还提到了生成firebase令牌。 您也可以尝试通过主题而不是Firebase令牌推送通知。