在Android中,使用FCM(Firebase Cloud Messaging)发送通知消息时,可以使用“notification”键来指定通知的标题、内容和其他属性。以下是一个示例代码,演示如何使用“notification”键发送通知消息:
// 创建一个JSON对象,用于构建通知消息
JSONObject notification = new JSONObject();
try {
// 设置通知标题
notification.put("title", "Notification Title");
// 设置通知内容
notification.put("body", "Notification Body");
// 设置通知图标(可选)
notification.put("icon", "icon_name");
// 创建一个JSON对象,用于构建完整的消息
JSONObject message = new JSONObject();
// 设置消息主体
message.put("data", data);
// 设置通知
message.put("notification", notification);
// 构建请求
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.POST,
"https://fcm.googleapis.com/fcm/send",
message,
new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
// 消息发送成功
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// 消息发送失败
}
}
) {
@Override
public Map getHeaders() throws AuthFailureError {
// 设置请求头,包含FCM服务器密钥
Map headers = new HashMap<>();
headers.put("Authorization", "key=YOUR_SERVER_KEY");
headers.put("Content-Type", "application/json");
return headers;
}
};
// 发送请求
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
} catch (JSONException e) {
e.printStackTrace();
}
上述代码中,使用JSONObject创建了一个包含通知标题、内容和其他属性的JSON对象。然后,创建了一个包含消息主体和通知的JSON对象,并使用JsonObjectRequest发送POST请求到FCM服务器。
需要注意以下几点:
"Notification Title"和"Notification Body"为实际的通知标题和内容。"icon_name"替换为实际的图标名称。"YOUR_SERVER_KEY"为实际的FCM服务器密钥,该密钥可在Firebase控制台中获取。这是一种使用“notification”键发送通知消息的解决方法。根据具体需求,您还可以添加其他属性,例如点击通知后的跳转链接等。