我正在尝试向用户发送通知,但是我不确定我是否使用正确的方法,因为从运行此代码开始,firebases控制台中没有新的通知。我可以传递目的地,标题和正文的令牌,但是不确定发帖请求是否正确。任何建议都将非常感谢。
public class ClientNotifications extends AsyncTask<String, Void, String> {
String token;
String titles;
String body;
public ClientNotifications(String token,String title,String body)
{
this.token = token;
this.titles=title;
this.body=body;
}
@Override
protected String doInBackground(String[] params) {
JsonObject jsonObj = new JsonObject();
// client registration key is sent as token in the message to FCM server
jsonObj.addProperty("token", token);
JsonObject notification = new JsonObject();
notification.addProperty("body", body);
notification.addProperty("title", titles);
jsonObj.add("notification", notification);
JsonObject message = new JsonObject();
message.add("message", jsonObj);
final MediaType mediaType = MediaType.parse("application/json");
OkHttpClient httpClient = new OkHttpClient();
try {
Request request = new Request.Builder().url("https://fcm.googleapis.com/v1/projects/yourfirebaseproject/messages:send")
.addHeader("Content-Type", "application/json; UTF-8")
.addHeader("Authorization", "Bearer " + "key")
.post(RequestBody.create(mediaType, message.toString())).build();
Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
}
} catch (IOException e) {
Log.e("HI",e.toString());
}
return message.toString();
}
@Override
protected void onPostExecute(String message) {
}
}
答案 0 :(得分:1)
这行不通:
.addHeader("Authorization", "Bearer " + "key")
您需要在此处传递实际的服务器密钥,而不仅仅是字符串“ key”。
值得指出的是,您不应该将此密钥提供给客户端应用程序,因为这是一个安全漏洞。最终用户永远都不能拥有授予对API特权访问权限的服务器密钥。您的客户端应用应改为调用安全后端来完成发送消息的工作。
我还要指出,您实际上并不是在检查请求中的错误。调用FCM的结果应该更详细地告诉您您做错了什么(但传递字符串“ key”绝对不正确)。
答案 1 :(得分:0)
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty("to", token);
jsonObj.addProperty("content-available", true);
jsonObj.addProperty("priority", "high");
JsonObject notification = new JsonObject();
notification.addProperty("body", body);
notification.addProperty("title", titles);
jsonObj.add("notification", notification);
final MediaType mediaType = MediaType.parse("application/json");
OkHttpClient httpClient = new OkHttpClient();
try {
Request request = new Request.Builder().url("https://fcm.googleapis.com/fcm/send")
.addHeader("Content-Type", "application/json; UTF-8")
.addHeader("Authorization", "key=your_key")
.post(RequestBody.create(mediaType, jsonObj.toString())).build();
Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
}
} catch (IOException e) {
Log.e("HI",e.toString());
}
我固定了我所看到的。祝你好运