|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- package com.example.erdbebensender;
-
- import android.content.Context;
- import android.nfc.Tag;
- import android.util.Log;
- import com.android.volley.*;
- import com.android.volley.toolbox.*;
- import org.json.JSONException;
- import org.json.JSONObject;
-
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.nio.charset.StandardCharsets;
-
-
- public class MessageSender {
-
- private static final String FCM_API = "https://fcm.googleapis.com/fcm/send";
- private static final String TOPIC = "erdbeben";
- private static final String SERVER_KEY = "AAAA2pVhMk4:APA91bHeiZGBd0BZi-RqnlCqnMkD7ICFW7SKzft-j1RIm16LX4M0Jez8AUQOoGgKYhHsVDD1kDxfKnul9Xbcjwo6QDAnPNLqOnk3XViVI5HjxgL8mpyzDLZXFharMIaqPANqBiMs5Gm2";
-
- private static final String TAG = "ErdbebenMessage";
-
-
- public void sendMessage(ErdbebenParameter erdbebenParameter) throws IOException, JSONException {
- URL url = new URL(FCM_API);
- HttpURLConnection con = (HttpURLConnection) url.openConnection();
- try {
- Log.i(TAG, "Init HTTP Request");
- con.setRequestMethod("POST");
- con.setRequestProperty("Content-Type", "application/json");
- //con.setRequestProperty("Accept", "application/json");
- con.setRequestProperty("Authorization", "key=" + SERVER_KEY);
- con.setDoOutput(true);
- //con.setChunkedStreamingMode(0);
- Log.i(TAG, "---Fehlerstelle kommt----");
- OutputStream out = new BufferedOutputStream(con.getOutputStream());
- Log.i(TAG, "---Fehler behoben---");
- out.write("Test".getBytes(),0, "Test".getBytes().length);
- out.flush();
- out.close();
-
- Log.i(TAG, "Request Erfolgreich gesendet");
-
- try (BufferedReader br = new BufferedReader(
- new InputStreamReader(con.getInputStream(), "utf-8"))) {
- StringBuilder response = new StringBuilder();
- String responseLine = null;
- while ((responseLine = br.readLine()) != null) {
- response.append(responseLine.trim());
- }
- Log.i(TAG, "Response erhalten: ");
- }
-
- } catch (Exception e) {
- throw e;
- }
- finally {
- con.disconnect();
- }
- }
-
- private JSONObject generateJson(ErdbebenParameter erdbebenParameter) throws JSONException {
- Log.i(TAG, "Erstelle JSON");
- JSONObject json = new JSONObject();
- JSONObject data = new JSONObject();
- JSONObject notification = new JSONObject();
-
- notification.put("title", "Erdbeben");
- notification.put("body", "Neues Erdbebeben aufgetretten");
- data.put("sender", erdbebenParameter.getSender());
- data.put("x", erdbebenParameter.getX());
- data.put("y", erdbebenParameter.getY());
- data.put("v", erdbebenParameter.getV());
-
- json.put("to", "/topics/" + TOPIC);
- json.put("notification", notification);
- json.put("data", data);
-
- return json;
- }
- }
|