我找到了我的問題從stackoverflow的答案。我希望這也能爲你工作。此代碼將消息和令牌ID發送到服務器。
public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
public final static String AUTH_KEY_FCM = "your key here";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
public void onTokenRefresh() {
String token = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Token: " + token);
}
public void sendAndroidNotification(String deviceToken, String message, String title) throws IOException {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
JSONObject obj = new JSONObject();
JSONObject msgObject = new JSONObject();
try {
msgObject.put("body", message);
Log.d("Body",message);
} catch (JSONException e) {
e.printStackTrace();
}
try {
msgObject.put("title", title);
Log.d("Title",title);
} catch (JSONException e) {
e.printStackTrace();
}
try {
msgObject.put("icon", R.mipmap.ic_launcher);
} catch (JSONException e) {
e.printStackTrace();
}
// msgObject.put("color",);
try {
obj.put("to", deviceToken);
Log.d("to",deviceToken);
} catch (JSONException e) {
e.printStackTrace();
}
try {
obj.put("notification",msgObject);
Log.d("Body",msgObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody body = RequestBody.create(mediaType, obj.toString());
Request request = new Request.Builder().url(API_URL_FCM).post(body)
.addHeader("content-type", CONTENT_TYPE)
.addHeader("authorization", "key="+AUTH_KEY_FCM).build();
Log.d("Request",body.toString());
Response response = client.newCall(request).execute();
Log.d("Notification response",response.body().string());
}
}
是否要將您的令牌ID存儲在Firebase服務器上或您自己的? – Hamza
@AmeerHamza我想在Firebase服務器上存儲 –
下面的答案有幫助嗎?或者,您仍然有問題需要存儲到Firebase服務器中。 –