有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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;
}
}

共 (1) 个答案