java - 如何获取我的计算机的设备令牌?
问题描述
我正在尝试创建一个小型应用程序,它将读取计算机/笔记本电脑的 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;
}
}
解决方案
您必须尝试https://firebase.google.com/docs/cloud-messaging/js/client为 firebase 推送通知创建 Web 客户端。在上面的文章中,也提到了生成 Firebase 令牌。您也可以尝试通过主题而不是 firebase 令牌推送通知。
推荐阅读
- javascript - 如何让不和谐机器人编辑 dm 消息?
- command-line - 如何仅将时间戳与 WinSCP 同步?
- php - 带有 PHP-FPM 的容器 nginx 不执行 PHP 文件
- ansible - 用 cisco ios 运行 ansible 只能看到一部分输出
- javascript - 在重叠的 div 周围环绕文本
- visual-studio-code - Flutter 找不到模拟器所需的文件
- javascript - 用 Python 加密和用 Javascript 解密的问题
- visual-studio - 断点是纯红色的,但永远不会被命中。调用 Debugger.Launch() 要求在新的 VS2019 窗口中以管理员身份运行 Just In Time Debugger
- ios - navigationBarTitle 与 SwiftUI 中的列表标题重叠
- python - 有没有办法让不和谐的机器人自动做某事(没有消息)?