首页 > 解决方案 > 无法在 Android 应用中生成 FCM 通知

问题描述

我需要帮助,我开发了一个基于社交的应用程序,它有一个聊天模块,用户可以发送和接收消息,但我无法生成通知。当我发送一条消息作为响应时,我对凌空错误函数得到“null”,下面是我的代码,因为我正在使用 FCM 服务。

private void sendNotification(final String hisId, final String hisName, final String message) {
    DatabaseReference allTokens = FirebaseDatabase.getInstance().getReference().child("new").child("Tokens");
    Query query = allTokens.orderByKey().equalTo(hisId);
    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                Token token = ds.getValue(Token.class);
                //(String user, String body, String title, String sent, Integer icon)
                Data data = new Data(myId, hisId + ": " + message, "New Message", hisName, R.drawable.image_icon);
                Sender sender = new Sender(data, token.getToken());

                try {
                    JSONObject senderJSONObject = new JSONObject(new Gson().toJson(sender));
                    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(URL, senderJSONObject,
                            new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    //response of the request
                                    Log.i("FCM", "onResponseFCM:" + response.toString());
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.i("FCM", error.getLocalizedMessage() + error.getNetworkTimeMs());
                            Toast.makeText(ChatActivity.this, "VolleyError: " + error.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            // Put params
                            Map<String, String> header = new HashMap<>();
                            header.put("content-type", "application/json");
                            header.put("authorization", "key=myKey");
                            return header;

                        }
                    };
                    // add this request to queue
                    requestQueue.add(jsonObjectRequest);
                } catch (JSONException e) {
                    Toast.makeText(ChatActivity.this, "FCM Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

以下是我在发送消息时得到的日志:

2020-05-25 10:23:52.509 505-1269/com.aadi.developers.asspass E/Volley: [11326] BasicNetwork.performRequest: Unexpected response code 401 for https://fcm.googleapis.com/fcm/send
2020-05-25 10:23:53.311 505-1269/com.aadi.developers.asspass E/Volley: [11326] BasicNetwork.performRequest: Unexpected response code 401 for https://fcm.googleapis.com/fcm/send
2020-05-25 10:23:53.315 505-505/com.aadi.developers.asspass I/FCM: null1901

Firebase 消息类是:

公共类 FirebaseMessaging 扩展 FirebaseMessagingService {

@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    SharedPreferences sp = getSharedPreferences("SP_USER", MODE_PRIVATE);
    String savedCurrentUser = sp.getString("Current_USERID", "None");
    String sent = remoteMessage.getData().get("sent");
    String user = remoteMessage.getData().get("user");

    FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser();
    if (fUser != null && sent.equals(fUser.getUid())) {
        if (!savedCurrentUser.equals(user)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                sendOreoAndAboveNotification(remoteMessage);
            } else {
                sendNormalNotification(remoteMessage);
            }
        }
    }
}

private void sendNormalNotification(RemoteMessage remoteMessage) {
    String user = remoteMessage.getData().get("user");
    String icon = remoteMessage.getData().get("icon");
    String title = remoteMessage.getData().get("title");
    String body = remoteMessage.getData().get("body");

    RemoteMessage.Notification notification = remoteMessage.getNotification();
    int i = Integer.parseInt(user.replaceAll("[\\D]", ""));
    Intent intent = new Intent(this, ChatActivity.class);
    Bundle bundle = new Bundle();
    bundle.putString("hisId", user);
    intent.putExtras(bundle);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pIntent = PendingIntent.getActivity(this, i, intent, PendingIntent.FLAG_ONE_SHOT);

    Uri defSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(Integer.parseInt(icon))
            .setContentText(body)
            .setContentTitle(title)
            .setAutoCancel(true)
            .setSound(defSoundUri)
            .setContentIntent(pIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    int j = 0;
    if (i > 0) {
        j = 1;
    }
    notificationManager.notify(j, builder.build());
}

@RequiresApi(api = Build.VERSION_CODES.O)
private void sendOreoAndAboveNotification(RemoteMessage remoteMessage) {
    String user = "" + remoteMessage.getData().get("user");
    String icon = "" + remoteMessage.getData().get("icon");
    String title = "" + remoteMessage.getData().get("title");
    String body = "" + remoteMessage.getData().get("body");

    RemoteMessage.Notification notification = remoteMessage.getNotification();
    int i = Integer.parseInt(user.replaceAll("[\\D]", ""));
    Intent intent = new Intent(this, ChatActivity.class);
    Bundle bundle = new Bundle();
    bundle.putString("hisId", user);
    intent.putExtras(bundle);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pIntent = PendingIntent.getActivity(this, i, intent, PendingIntent.FLAG_ONE_SHOT);

    Uri defSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    OreoAndOverNotification notification1 = new OreoAndOverNotification(this);
    Notification.Builder builder = notification1.getONotifications(title, body, pIntent, defSoundUri, icon);

    int j = 0;
    if (i > 0) {
        j = 1;
    }
    notification1.getManager().notify(j, builder.build());
}

@Override
public void onNewToken(@NonNull String s) {
    super.onNewToken(s);
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user != null) {
        updateToken(s);
    }
}

private void updateToken(String tokenRefresh) {
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Tokens");
    Token token = new Token(tokenRefresh);
    ref.child(user.getUid()).setValue(token);
}

}

标签: androidfirebasegoogle-cloud-functionsfirebase-cloud-messagingchat

解决方案


**在我的情况下,在 FCM_KEY 解决我的问题之前 Puttin "key="。也很肯定这是主要问题。如果你得到 401 错误。我是这样写的:

params.put("Authorization", FCM_KEY);

但真正的解决方案是:

params.put("Authorization","key=" FCM_KEY);

**

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> params = new HashMap<>();
    params.put("Authorization", "key=" + FCM_KEY);
    params.put("Content-Type", "application/json");
    return params;
}

};


推荐阅读