如何将Java项目导入Firebase并创建数据库?

时间:2017-06-06 06:08:20

标签: java mysql firebase firebase-realtime-database

我用MySQL数据库构建了java项目。我想将这个java项目导入firebase。请指导如何在firebase中创建数据库以及如何将java ready项目导入firebase?

1 个答案:

答案 0 :(得分:0)

首次访问https://firebase.google.com/了解更多详情 然后根据您所需的平台创建一个新项目。

在服务器端创建一个用于存储用户FCM密钥的表

Table: fcmkeys
Columns:
user varchar(10) PK 
fcmkey varchar(1045) 

生成FCM_AUTH_KEY 创建一个类似

的Java Helper类
public class FCMHelper {

    static Logger log = Logger.getLogger(FCMHelper.class);
    // Method to send Notifications from server to client end.

    public final static String AUTH_KEY_FCM = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";

    // userDeviceIdKey is the device id you will query from your database

    public static void pushFCMNotification(String userDeviceIdKey ,String NotificationString) throws Exception{

       String authKey = AUTH_KEY_FCM; // You FCM AUTH key
       String FMCurl = API_URL_FCM; 

       URL url = new URL(FMCurl);
       HttpURLConnection conn = (HttpURLConnection) url.openConnection();

       conn.setUseCaches(false);
       conn.setDoInput(true);
       conn.setDoOutput(true);

       conn.setRequestMethod("POST");
       conn.setRequestProperty("Authorization","key="+authKey);
       conn.setRequestProperty("Content-Type","application/json");

       JSONObject json = new JSONObject();
       json.put("to",userDeviceIdKey.trim());
       JSONObject info = new JSONObject();
      // info.put("title", "Alert!"); // Notification title
       info.put("body", NotificationString); // Notification body
       json.put("data", info);

       OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
       wr.write(json.toString());
       wr.flush();
       conn.getInputStream();
       System.out.println("Notification Send Success!");
       System.out.println( conn.getInputStream().toString());

       InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();

        String inputStr;
        while ((inputStr = streamReader.readLine()) != null)
            responseStrBuilder.append(inputStr);
        String s = responseStrBuilder.toString();
         System.out.println( s);
         log.info(s);

    }
}

此Helper类可以向客户端发送FCM通知