Advertisement
Guest User

Untitled

a guest
Jul 17th, 2017
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.51 KB | None | 0 0
  1. public static final MediaType JSON
  2. = MediaType.parse("application/json; charset=utf-8");
  3. private void sendNotification(final String reg_token) {
  4. new AsyncTask<Void,Void,Void>(){
  5. @Override
  6. protected Void doInBackground(Void... params) {
  7. try {
  8. OkHttpClient client = new OkHttpClient();
  9. JSONObject json=new JSONObject();
  10. JSONObject dataJson=new JSONObject();
  11. dataJson.put("body","Hi this is sent from device to device");
  12. dataJson.put("title","dummy title");
  13. json.put("notification",dataJson);
  14. json.put("to",regToken);
  15. RequestBody body = RequestBody.create(JSON, json.toString());
  16. Request request = new Request.Builder()
  17. .header("Authorization","key="+Constants.LEGACY_SERVER_KEY)
  18. .url("https://fcm.googleapis.com/fcm/send")
  19. .post(body)
  20. .build();
  21. Response response = client.newCall(request).execute();
  22. String finalResponse = response.body().string();
  23. }catch (Exception e){
  24. //Log.d(TAG,e+"");
  25. }
  26. return null;
  27. }
  28. }.execute();
  29.  
  30. }
  31.  
  32. json.put("to","/topics/foo-bar")
  33.  
  34. private void sendFCMPush() {
  35.  
  36. String Legacy_SERVER_KEY = YOUR_Legacy_SERVER_KEY;
  37. String msg = "this is test message,.,,.,.";
  38. String title = "my title";
  39. String token = FCM_RECEIVER_TOKEN;
  40.  
  41. JSONObject obj = null;
  42. JSONObject objData = null;
  43. JSONObject dataobjData = null;
  44.  
  45. try {
  46. obj = new JSONObject();
  47. objData = new JSONObject();
  48.  
  49. objData.put("body", msg);
  50. objData.put("title", title);
  51. objData.put("sound", "default");
  52. objData.put("icon", "icon_name"); // icon_name image must be there in drawable
  53. objData.put("tag", token);
  54. objData.put("priority", "high");
  55.  
  56. dataobjData = new JSONObject();
  57. dataobjData.put("text", msg);
  58. dataobjData.put("title", title);
  59.  
  60. obj.put("to", token);
  61. //obj.put("priority", "high");
  62.  
  63. obj.put("notification", objData);
  64. obj.put("data", dataobjData);
  65. Log.e("!_@rj@_@@_PASS:>", obj.toString());
  66. } catch (JSONException e) {
  67. e.printStackTrace();
  68. }
  69.  
  70. JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, Constants.FCM_PUSH_URL, obj,
  71. new Response.Listener<JSONObject>() {
  72. @Override
  73. public void onResponse(JSONObject response) {
  74. Log.e("!_@@_SUCESS", response + "");
  75. }
  76. },
  77. new Response.ErrorListener() {
  78. @Override
  79. public void onErrorResponse(VolleyError error) {
  80. Log.e("!_@@_Errors--", error + "");
  81. }
  82. }) {
  83. @Override
  84. public Map<String, String> getHeaders() throws AuthFailureError {
  85. Map<String, String> params = new HashMap<String, String>();
  86. params.put("Authorization", "key=" + Legacy_SERVER_KEY);
  87. params.put("Content-Type", "application/json");
  88. return params;
  89. }
  90. };
  91. RequestQueue requestQueue = Volley.newRequestQueue(this);
  92. int socketTimeout = 1000 * 60;// 60 seconds
  93. RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
  94. jsObjRequest.setRetryPolicy(policy);
  95. requestQueue.add(jsObjRequest);
  96. }
  97.  
  98. public void onClick(View view) {
  99.  
  100. HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
  101. logging.setLevel(HttpLoggingInterceptor.Level.BODY);
  102.  
  103. OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
  104. httpClient.addInterceptor(new Interceptor() {
  105. @Override
  106. public okhttp3.Response intercept(Chain chain) throws IOException {
  107. Request original = chain.request();
  108.  
  109. // Request customization: add request headers
  110. Request.Builder requestBuilder = original.newBuilder()
  111. .header("Authorization", "key=legacy server key from FB console"); // <-- this is the important line
  112. Request request = requestBuilder.build();
  113. return chain.proceed(request);
  114. }
  115. });
  116.  
  117. httpClient.addInterceptor(logging);
  118. OkHttpClient client = httpClient.build();
  119.  
  120. Retrofit retrofit = new Retrofit.Builder()
  121. .baseUrl("https://fcm.googleapis.com")//url of FCM message server
  122. .client(client)
  123. .addConverterFactory(GsonConverterFactory.create())//use for convert JSON file into object
  124. .build();
  125.  
  126. // prepare call in Retrofit 2.0
  127. FirebaseAPI firebaseAPI = retrofit.create(FirebaseAPI.class);
  128.  
  129. //for messaging server
  130. NotifyData notifydata = new NotifyData("Notification title","Notification body");
  131.  
  132. Call<Message> call2 = firebaseAPI.sendMessage(new Message("topic or deviceID", notifydata));
  133.  
  134. call2.enqueue(new Callback<Message>() {
  135. @Override
  136. public void onResponse(Call<Message> call, Response<Message> response) {
  137.  
  138. Log.d("Response ", "onResponse");
  139. t1.setText("Notification sent");
  140.  
  141. }
  142.  
  143. @Override
  144. public void onFailure(Call<Message> call, Throwable t) {
  145. Log.d("Response ", "onFailure");
  146. t1.setText("Notification failure");
  147. }
  148. });
  149. }
  150.  
  151. public class Message {
  152. String to;
  153. NotifyData notification;
  154.  
  155. public Message(String to, NotifyData notification) {
  156. this.to = to;
  157. this.notification = notification;
  158. }
  159.  
  160. }
  161.  
  162. public class NotifyData {
  163. String title;
  164. String body;
  165.  
  166. public NotifyData(String title, String body ) {
  167.  
  168. this.title = title;
  169. this.body = body;
  170. }
  171.  
  172. }
  173.  
  174. public interface FirebaseAPI {
  175.  
  176. @POST("/fcm/send")
  177. Call<Message> sendMessage(@Body Message message);
  178.  
  179. }
  180.  
  181. public class FcmDeviceNotifier {
  182.  
  183. private final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  184. private final String TAG = FcmDeviceNotifier.class.getSimpleName();
  185. private String requestType;
  186. private JSONObject payloadJson;
  187.  
  188. public FcmDeviceNotifier(String requestType /*can be "notification" or "data"*/) {
  189. this.requestType = requestType;
  190. }
  191.  
  192. public void setValuePairs(Map<String, String> valuePairs) {
  193. try {
  194. payloadJson = new JSONObject();
  195. Iterator<Map.Entry<String,String>> iterator = valuePairs.entrySet().iterator();
  196. while (iterator.hasNext()) {
  197. Map.Entry<String,String> entry = iterator.next();
  198. payloadJson.put(entry.getKey(), entry.getValue());
  199. }
  200. } catch (JSONException e) {
  201. e.printStackTrace();
  202. }
  203. }
  204.  
  205. public void sendNotification(final String regToken /*Token of target device*/) {
  206. new AsyncTask<Void,Void,Void>(){
  207. @Override
  208. protected Void doInBackground(Void... params) {
  209. try {
  210. OkHttpClient client = new OkHttpClient();
  211. JSONObject fcmJson = new JSONObject();
  212. fcmJson.put(requestType, payloadJson);
  213. fcmJson.put(TO, regToken);
  214. RequestBody body = RequestBody.create(JSON, fcmJson.toString());
  215. Request request = new Request.Builder()
  216. .header(AUTHORIZATION, "key=" + Constants.FCM_LEGACY_KEY)
  217. .url("https://fcm.googleapis.com/fcm/send")
  218. .post(body)
  219. .build();
  220. Response response = client.newCall(request).execute();
  221. String finalResponse = response.body().string();
  222. Log.d(TAG, "sendNotification: " + finalResponse);
  223. }catch (Exception e){
  224. Log.e(TAG, "sendNotification: " + e.getMessage());
  225. }
  226. return null;
  227. }
  228. }.execute();
  229. }
  230.  
  231. private String mTitle;
  232. private String mMessage;
  233. private String mUsername;
  234. private String mUid;
  235. private String mFirebaseToken;
  236. private String mReceiverFirebaseToken;
  237.  
  238. private FcmNotificationBuilder() {
  239.  
  240. }
  241.  
  242. public static FcmNotificationBuilder initialize() {
  243. return new FcmNotificationBuilder();
  244. }
  245.  
  246. public FcmNotificationBuilder title(String title) {
  247. mTitle = title;
  248. return this;
  249. }
  250.  
  251. public FcmNotificationBuilder message(String message) {
  252. mMessage = message;
  253. return this;
  254. }
  255.  
  256. public FcmNotificationBuilder username(String username) {
  257. mUsername = username;
  258. return this;
  259. }
  260.  
  261. public FcmNotificationBuilder uid(String uid) {
  262. mUid = uid;
  263. return this;
  264. }
  265.  
  266. public FcmNotificationBuilder firebaseToken(String firebaseToken) {
  267. mFirebaseToken = firebaseToken;
  268. return this;
  269. }
  270.  
  271. public FcmNotificationBuilder receiverFirebaseToken(String receiverFirebaseToken) {
  272. mReceiverFirebaseToken = receiverFirebaseToken;
  273. return this;
  274. }
  275.  
  276. public void send() {
  277. RequestBody requestBody = null;
  278. try {
  279. requestBody = RequestBody.create(MEDIA_TYPE_JSON, getValidJsonBody().toString());
  280. } catch (JSONException e) {
  281. e.printStackTrace();
  282. }
  283.  
  284. Request request = new Request.Builder()
  285. .addHeader(CONTENT_TYPE, APPLICATION_JSON)
  286. .addHeader(AUTHORIZATION, AUTH_KEY)
  287. .url(FCM_URL)
  288. .post(requestBody)
  289. .build();
  290.  
  291. Call call = new OkHttpClient().newCall(request);
  292. call.enqueue(new Callback() {
  293. @Override
  294. public void onFailure(Call call, IOException e) {
  295. Log.e(TAG, "onGetAllUsersFailure: " + e.getMessage());
  296. }
  297.  
  298. @Override
  299. public void onResponse(Call call, Response response) throws IOException {
  300. Log.e(TAG, "onResponse: " + response.body().string());
  301. }
  302. });
  303. }
  304.  
  305. private JSONObject getValidJsonBody() throws JSONException {
  306. JSONObject jsonObjectBody = new JSONObject();
  307. jsonObjectBody.put(KEY_TO, mReceiverFirebaseToken);
  308.  
  309. JSONObject jsonObjectData = new JSONObject();
  310. jsonObjectData.put(KEY_TITLE, mTitle);
  311. jsonObjectData.put(KEY_TEXT, mMessage);
  312. jsonObjectData.put(KEY_USERNAME, mUsername);
  313. jsonObjectData.put(KEY_UID, mUid);
  314. jsonObjectData.put(KEY_FCM_TOKEN, mFirebaseToken);
  315. jsonObjectBody.put(KEY_DATA, jsonObjectData);
  316. return jsonObjectBody;
  317. }
  318.  
  319. void sendFCMPush(String msg,String token) {
  320. HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
  321. logging.setLevel(HttpLoggingInterceptor.Level.BODY);
  322.  
  323. OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
  324. httpClient.addInterceptor(new Interceptor() {
  325. @Override
  326. public okhttp3.Response intercept(Chain chain) throws IOException {
  327. Request original = chain.request();
  328.  
  329. // Request customization: add request headers
  330. Request.Builder requestBuilder = original.newBuilder()
  331. .header("Authorization", "key="+Const.FIREBASE_LEGACY_SERVER_KEY); // <-- this is the important line
  332. Request request = requestBuilder.build();
  333. return chain.proceed(request);
  334. }
  335. });
  336.  
  337. httpClient.addInterceptor(logging);
  338. OkHttpClient client = httpClient.build();
  339.  
  340. Retrofit retrofit = new Retrofit.Builder()
  341. .baseUrl("https://fcm.googleapis.com/")//url of FCM message server
  342. .client(client)
  343. .addConverterFactory(GsonConverterFactory.create())//use for convert JSON file into object
  344. .build();
  345.  
  346. // prepare call in Retrofit 2.0
  347. FirebaseAPI firebaseAPI = retrofit.create(FirebaseAPI.class);
  348.  
  349. //for messaging server
  350. NotifyData notifydata = new NotifyData("Chatting", msg);
  351.  
  352. Call<Message> call2 = firebaseAPI.sendMessage(new Message(token, notifydata));
  353.  
  354. call2.enqueue(new Callback<Message>() {
  355. @Override
  356. public void onResponse(Call<Message> call, retrofit2.Response<Message> response) {
  357. Log.e("#@ SUCCES #E$#", response.body().toString());
  358. }
  359.  
  360. @Override
  361. public void onFailure(Call<Message> call, Throwable t) {
  362.  
  363. Log.e("E$ FAILURE E$#", t.getMessage());
  364. }
  365. });
  366. }
  367.  
  368. public class Message {
  369. String to;
  370. NotifyData data;
  371.  
  372. public Message(String to, NotifyData data) {
  373. this.to = to;
  374. this.data = data;
  375. }
  376. }
  377.  
  378. public class Notification {
  379. String title;
  380. String message;
  381. enter code here`enter code here`
  382. public Notification(String title, String message) {
  383. this.title = title;
  384. this.message = message;
  385. }
  386. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement