How to send upstream messages with FCM from android client?

前端 未结 2 1082
误落风尘
误落风尘 2021-02-10 00:19

We were using GoogleCloudMessaging.getInstance(context).send(context.getString(R.string.gcm_defaultSenderId) + \"@gcm.googleapis.com\", mId, mBundle); to send upstr

2条回答
  •  醉酒成梦
    2021-02-10 00:55

    Well 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).toString());
              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);
              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.

提交回复
热议问题