How to send one to one message using Firebase Messaging

后端 未结 5 1479
Happy的楠姐
Happy的楠姐 2020-11-22 04:30

I have been trying to read the official docs and guides about how to send message from one device to another. I have saved registration token of both devices in the Real Tim

5条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 05:19

    I am late but above solutions has helped me to write down this simple answer, you can send your message directly to android devices from android application, here is the simple implementation I have done and it works great for me.

    1. compile android volley library

      compile 'com.android.volley:volley:1.0.0'
      
    2. Just copy paste this simple function ;) and your life will become smooth just like knife in butter. :D

      public static void sendPushToSingleInstance(final Context activity, final HashMap dataValue /*your data from the activity*/, final String instanceIdToken /*firebase instance token you will find in documentation that how to get this*/ ) {
      
      
      final String url = "https://fcm.googleapis.com/fcm/send";
      StringRequest myReq = new StringRequest(Request.Method.POST,url,
              new Response.Listener() {
                  @Override
                  public void onResponse(String response) {
                      Toast.makeText(activity, "Bingo Success", Toast.LENGTH_SHORT).show();
                  }
              },
              new Response.ErrorListener() {
                  @Override
                  public void onErrorResponse(VolleyError error) {
                      Toast.makeText(activity, "Oops error", Toast.LENGTH_SHORT).show();
                  }
              }) {
      
          @Override
          public byte[] getBody() throws com.android.volley.AuthFailureError {
              Map rawParameters = new Hashtable();
              rawParameters.put("data", new JSONObject(dataValue));
              rawParameters.put("to", instanceIdToken);
              return new JSONObject(rawParameters).toString().getBytes();
          };
      
          public String getBodyContentType()
          {
              return "application/json; charset=utf-8";
          }
          @Override
          public Map getHeaders() throws AuthFailureError {
              HashMap headers = new HashMap();
              headers.put("Authorization", "key="+YOUR_LEGACY_SERVER_KEY_FROM_FIREBASE_CONSOLE);
              headers.put("Content-Type","application/json");
              return headers;
          }
      
      };
      
      Volley.newRequestQueue(activity).add(myReq);
      }
      

    Note If you want to send message to topics so you can change parameter instanceIdToken to something like /topics/topicName. For groups implementation is the same but you just need to take care of parameters. checkout Firebase documentation and you can pass those parameters. let me know if you face any issue.

提交回复
热议问题