Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static final MediaType JSON
- = MediaType.parse("application/json; charset=utf-8");
- private void sendNotification(final String reg_token) {
- new AsyncTask<Void,Void,Void>(){
- @Override
- protected Void doInBackground(Void... params) {
- try {
- OkHttpClient client = new OkHttpClient();
- JSONObject json=new JSONObject();
- JSONObject dataJson=new JSONObject();
- dataJson.put("body","Hi this is sent from device to device");
- dataJson.put("title","dummy title");
- json.put("notification",dataJson);
- json.put("to",regToken);
- RequestBody body = RequestBody.create(JSON, json.toString());
- Request request = new Request.Builder()
- .header("Authorization","key="+Constants.LEGACY_SERVER_KEY)
- .url("https://fcm.googleapis.com/fcm/send")
- .post(body)
- .build();
- Response response = client.newCall(request).execute();
- String finalResponse = response.body().string();
- }catch (Exception e){
- //Log.d(TAG,e+"");
- }
- return null;
- }
- }.execute();
- }
- json.put("to","/topics/foo-bar")
- private void sendFCMPush() {
- String Legacy_SERVER_KEY = YOUR_Legacy_SERVER_KEY;
- String msg = "this is test message,.,,.,.";
- String title = "my title";
- String token = FCM_RECEIVER_TOKEN;
- JSONObject obj = null;
- JSONObject objData = null;
- JSONObject dataobjData = null;
- try {
- obj = new JSONObject();
- objData = new JSONObject();
- objData.put("body", msg);
- objData.put("title", title);
- objData.put("sound", "default");
- objData.put("icon", "icon_name"); // icon_name image must be there in drawable
- objData.put("tag", token);
- objData.put("priority", "high");
- dataobjData = new JSONObject();
- dataobjData.put("text", msg);
- dataobjData.put("title", title);
- obj.put("to", token);
- //obj.put("priority", "high");
- obj.put("notification", objData);
- obj.put("data", dataobjData);
- Log.e("!_@rj@_@@_PASS:>", obj.toString());
- } catch (JSONException e) {
- e.printStackTrace();
- }
- JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, Constants.FCM_PUSH_URL, obj,
- new Response.Listener<JSONObject>() {
- @Override
- public void onResponse(JSONObject response) {
- Log.e("!_@@_SUCESS", response + "");
- }
- },
- new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- Log.e("!_@@_Errors--", error + "");
- }
- }) {
- @Override
- public Map<String, String> getHeaders() throws AuthFailureError {
- Map<String, String> params = new HashMap<String, String>();
- params.put("Authorization", "key=" + Legacy_SERVER_KEY);
- params.put("Content-Type", "application/json");
- return params;
- }
- };
- RequestQueue requestQueue = Volley.newRequestQueue(this);
- int socketTimeout = 1000 * 60;// 60 seconds
- RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
- jsObjRequest.setRetryPolicy(policy);
- requestQueue.add(jsObjRequest);
- }
- public void onClick(View view) {
- HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
- logging.setLevel(HttpLoggingInterceptor.Level.BODY);
- OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
- httpClient.addInterceptor(new Interceptor() {
- @Override
- public okhttp3.Response intercept(Chain chain) throws IOException {
- Request original = chain.request();
- // Request customization: add request headers
- Request.Builder requestBuilder = original.newBuilder()
- .header("Authorization", "key=legacy server key from FB console"); // <-- this is the important line
- Request request = requestBuilder.build();
- return chain.proceed(request);
- }
- });
- httpClient.addInterceptor(logging);
- OkHttpClient client = httpClient.build();
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl("https://fcm.googleapis.com")//url of FCM message server
- .client(client)
- .addConverterFactory(GsonConverterFactory.create())//use for convert JSON file into object
- .build();
- // prepare call in Retrofit 2.0
- FirebaseAPI firebaseAPI = retrofit.create(FirebaseAPI.class);
- //for messaging server
- NotifyData notifydata = new NotifyData("Notification title","Notification body");
- Call<Message> call2 = firebaseAPI.sendMessage(new Message("topic or deviceID", notifydata));
- call2.enqueue(new Callback<Message>() {
- @Override
- public void onResponse(Call<Message> call, Response<Message> response) {
- Log.d("Response ", "onResponse");
- t1.setText("Notification sent");
- }
- @Override
- public void onFailure(Call<Message> call, Throwable t) {
- Log.d("Response ", "onFailure");
- t1.setText("Notification failure");
- }
- });
- }
- public class Message {
- String to;
- NotifyData notification;
- public Message(String to, NotifyData notification) {
- this.to = to;
- this.notification = notification;
- }
- }
- public class NotifyData {
- String title;
- String body;
- public NotifyData(String title, String body ) {
- this.title = title;
- this.body = body;
- }
- }
- public interface FirebaseAPI {
- @POST("/fcm/send")
- Call<Message> sendMessage(@Body Message message);
- }
- public class FcmDeviceNotifier {
- private final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
- private final String TAG = FcmDeviceNotifier.class.getSimpleName();
- private String requestType;
- private JSONObject payloadJson;
- public FcmDeviceNotifier(String requestType /*can be "notification" or "data"*/) {
- this.requestType = requestType;
- }
- public void setValuePairs(Map<String, String> valuePairs) {
- try {
- payloadJson = new JSONObject();
- Iterator<Map.Entry<String,String>> iterator = valuePairs.entrySet().iterator();
- while (iterator.hasNext()) {
- Map.Entry<String,String> entry = iterator.next();
- payloadJson.put(entry.getKey(), entry.getValue());
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- public void sendNotification(final String regToken /*Token of target device*/) {
- new AsyncTask<Void,Void,Void>(){
- @Override
- protected Void doInBackground(Void... params) {
- try {
- OkHttpClient client = new OkHttpClient();
- JSONObject fcmJson = new JSONObject();
- fcmJson.put(requestType, payloadJson);
- fcmJson.put(TO, regToken);
- RequestBody body = RequestBody.create(JSON, fcmJson.toString());
- Request request = new Request.Builder()
- .header(AUTHORIZATION, "key=" + Constants.FCM_LEGACY_KEY)
- .url("https://fcm.googleapis.com/fcm/send")
- .post(body)
- .build();
- Response response = client.newCall(request).execute();
- String finalResponse = response.body().string();
- Log.d(TAG, "sendNotification: " + finalResponse);
- }catch (Exception e){
- Log.e(TAG, "sendNotification: " + e.getMessage());
- }
- return null;
- }
- }.execute();
- }
- private String mTitle;
- private String mMessage;
- private String mUsername;
- private String mUid;
- private String mFirebaseToken;
- private String mReceiverFirebaseToken;
- private FcmNotificationBuilder() {
- }
- public static FcmNotificationBuilder initialize() {
- return new FcmNotificationBuilder();
- }
- public FcmNotificationBuilder title(String title) {
- mTitle = title;
- return this;
- }
- public FcmNotificationBuilder message(String message) {
- mMessage = message;
- return this;
- }
- public FcmNotificationBuilder username(String username) {
- mUsername = username;
- return this;
- }
- public FcmNotificationBuilder uid(String uid) {
- mUid = uid;
- return this;
- }
- public FcmNotificationBuilder firebaseToken(String firebaseToken) {
- mFirebaseToken = firebaseToken;
- return this;
- }
- public FcmNotificationBuilder receiverFirebaseToken(String receiverFirebaseToken) {
- mReceiverFirebaseToken = receiverFirebaseToken;
- return this;
- }
- public void send() {
- RequestBody requestBody = null;
- try {
- requestBody = RequestBody.create(MEDIA_TYPE_JSON, getValidJsonBody().toString());
- } catch (JSONException e) {
- e.printStackTrace();
- }
- Request request = new Request.Builder()
- .addHeader(CONTENT_TYPE, APPLICATION_JSON)
- .addHeader(AUTHORIZATION, AUTH_KEY)
- .url(FCM_URL)
- .post(requestBody)
- .build();
- Call call = new OkHttpClient().newCall(request);
- call.enqueue(new Callback() {
- @Override
- public void onFailure(Call call, IOException e) {
- Log.e(TAG, "onGetAllUsersFailure: " + e.getMessage());
- }
- @Override
- public void onResponse(Call call, Response response) throws IOException {
- Log.e(TAG, "onResponse: " + response.body().string());
- }
- });
- }
- private JSONObject getValidJsonBody() throws JSONException {
- JSONObject jsonObjectBody = new JSONObject();
- jsonObjectBody.put(KEY_TO, mReceiverFirebaseToken);
- JSONObject jsonObjectData = new JSONObject();
- jsonObjectData.put(KEY_TITLE, mTitle);
- jsonObjectData.put(KEY_TEXT, mMessage);
- jsonObjectData.put(KEY_USERNAME, mUsername);
- jsonObjectData.put(KEY_UID, mUid);
- jsonObjectData.put(KEY_FCM_TOKEN, mFirebaseToken);
- jsonObjectBody.put(KEY_DATA, jsonObjectData);
- return jsonObjectBody;
- }
- void sendFCMPush(String msg,String token) {
- HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
- logging.setLevel(HttpLoggingInterceptor.Level.BODY);
- OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
- httpClient.addInterceptor(new Interceptor() {
- @Override
- public okhttp3.Response intercept(Chain chain) throws IOException {
- Request original = chain.request();
- // Request customization: add request headers
- Request.Builder requestBuilder = original.newBuilder()
- .header("Authorization", "key="+Const.FIREBASE_LEGACY_SERVER_KEY); // <-- this is the important line
- Request request = requestBuilder.build();
- return chain.proceed(request);
- }
- });
- httpClient.addInterceptor(logging);
- OkHttpClient client = httpClient.build();
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl("https://fcm.googleapis.com/")//url of FCM message server
- .client(client)
- .addConverterFactory(GsonConverterFactory.create())//use for convert JSON file into object
- .build();
- // prepare call in Retrofit 2.0
- FirebaseAPI firebaseAPI = retrofit.create(FirebaseAPI.class);
- //for messaging server
- NotifyData notifydata = new NotifyData("Chatting", msg);
- Call<Message> call2 = firebaseAPI.sendMessage(new Message(token, notifydata));
- call2.enqueue(new Callback<Message>() {
- @Override
- public void onResponse(Call<Message> call, retrofit2.Response<Message> response) {
- Log.e("#@ SUCCES #E$#", response.body().toString());
- }
- @Override
- public void onFailure(Call<Message> call, Throwable t) {
- Log.e("E$ FAILURE E$#", t.getMessage());
- }
- });
- }
- public class Message {
- String to;
- NotifyData data;
- public Message(String to, NotifyData data) {
- this.to = to;
- this.data = data;
- }
- }
- public class Notification {
- String title;
- String message;
- enter code here`enter code here`
- public Notification(String title, String message) {
- this.title = title;
- this.message = message;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement