You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MyFirebaseMessagingService.java 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. package com.example.fcm;
  2. import android.app.NotificationChannel;
  3. import android.app.NotificationManager;
  4. import android.app.PendingIntent;
  5. import android.content.Context;
  6. import android.content.Intent;
  7. import android.graphics.Color;
  8. import android.media.RingtoneManager;
  9. import android.net.Uri;
  10. import android.os.Build;
  11. import android.util.Log;
  12. import androidx.annotation.RequiresApi;
  13. import androidx.core.app.NotificationCompat;
  14. import androidx.work.OneTimeWorkRequest;
  15. import androidx.work.WorkManager;
  16. import com.google.firebase.messaging.FirebaseMessagingService;
  17. import com.google.firebase.messaging.RemoteMessage;
  18. import java.util.Random;
  19. public class MyFirebaseMessagingService extends FirebaseMessagingService {
  20. private final String ADMIN_CHANNEL_ID ="admin_channel";
  21. private static final String TAG = "MyFirebaseMsgService";
  22. private static final String FIREBASE_URL = "https://fcmfirebaseproject-ececa.firebaseio.com";
  23. /**
  24. * Called when message is received.
  25. *
  26. * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
  27. */
  28. // [START receive_message]
  29. @Override
  30. public void onMessageReceived(RemoteMessage remoteMessage) {
  31. // [START_EXCLUDE]
  32. // There are two types of messages data messages and notification messages. Data messages
  33. // are handled
  34. // here in onMessageReceived whether the app is in the foreground or background. Data
  35. // messages are the type
  36. // traditionally used with GCM. Notification messages are only received here in
  37. // onMessageReceived when the app
  38. // is in the foreground. When the app is in the background an automatically generated
  39. // notification is displayed.
  40. // When the user taps on the notification they are returned to the app. Messages
  41. // containing both notification
  42. // and data payloads are treated as notification messages. The Firebase console always
  43. // sends notification
  44. // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
  45. // [END_EXCLUDE]
  46. // TODO(developer): Handle FCM messages here.
  47. // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
  48. final Intent intent = new Intent(this, MainActivity.class);
  49. NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
  50. int notificationID = new Random().nextInt(3000);
  51. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
  52. setupChannels(notificationManager);
  53. }
  54. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  55. PendingIntent pendingIntent = PendingIntent.getActivity(this , 0, intent,
  56. PendingIntent.FLAG_ONE_SHOT);
  57. Uri notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
  58. NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
  59. .setSmallIcon(R.drawable.ic_stat_ic_notification)
  60. .setContentTitle(remoteMessage.getData().get("title"))
  61. .setContentText(remoteMessage.getData().get("message"))
  62. .setAutoCancel(true)
  63. .setSound(notificationSoundUri)
  64. .setContentIntent(pendingIntent);
  65. notificationManager.notify(notificationID, notificationBuilder.build());
  66. Log.d(TAG, "From: " + remoteMessage.getFrom());
  67. // Check if message contains a data payload.
  68. if (remoteMessage.getData().size() > 0) {
  69. Log.d(TAG, "Message data payload: " + remoteMessage.getData());
  70. if (/* Check if data needs to be processed by long running job */ true) {
  71. // For long-running tasks (10 seconds or more) use WorkManager.
  72. scheduleJob();
  73. } else {
  74. // Handle message within 10 seconds
  75. handleNow();
  76. }
  77. }
  78. // Check if message contains a notification payload.
  79. if (remoteMessage.getNotification() != null) {
  80. Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
  81. }
  82. // Also if you intend on generating your own notifications as a result of a received FCM
  83. // message, here is where that should be initiated. See sendNotification method below.
  84. }
  85. // [END receive_message]
  86. // [START on_new_token]
  87. /**
  88. * Called if InstanceID token is updated. This may occur if the security of
  89. * the previous token had been compromised. Note that this is called when the InstanceID token
  90. * is initially generated so this is where you would retrieve the token.
  91. */
  92. @Override
  93. public void onNewToken(String token) {
  94. Log.d(TAG, "Refreshed token: " + token);
  95. // If you want to send messages to this application instance or
  96. // manage this apps subscriptions on the server side, send the
  97. // Instance ID token to your app server.
  98. sendRegistrationToServer(token);
  99. }
  100. // [END on_new_token]
  101. /**
  102. * Schedule async work using WorkManager.
  103. */
  104. private void scheduleJob() {
  105. // [START dispatch_job]
  106. OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(MyWorker.class)
  107. .build();
  108. WorkManager.getInstance().beginWith(work).enqueue();
  109. // [END dispatch_job]
  110. }
  111. /**
  112. * Handle time allotted to BroadcastReceivers.
  113. */
  114. private void handleNow() {
  115. Log.d(TAG, "Short lived task is done.");
  116. }
  117. /**
  118. * Persist token to third-party servers.
  119. *
  120. * Modify this method to associate the user's FCM InstanceID token with any server-side account
  121. * maintained by your application.
  122. *
  123. * @param token The new token.
  124. */
  125. private void sendRegistrationToServer(String token) {
  126. // TODO: Implement this method to send token to your app server.
  127. }
  128. /**
  129. * Create and show a simple notification containing the received FCM message.
  130. *
  131. * @param messageBody FCM message body received.
  132. */
  133. private void sendNotification(String messageBody) {
  134. Intent intent = new Intent(this, MainActivity.class);
  135. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  136. PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
  137. PendingIntent.FLAG_ONE_SHOT);
  138. String channelId = getString(R.string.default_notification_channel_id);
  139. Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
  140. NotificationCompat.Builder notificationBuilder =
  141. new NotificationCompat.Builder(this, channelId)
  142. .setSmallIcon(R.drawable.ic_stat_ic_notification)
  143. .setContentTitle(getString(R.string.fcm_message))
  144. .setContentText(messageBody)
  145. .setAutoCancel(true)
  146. .setSound(defaultSoundUri)
  147. .setContentIntent(pendingIntent);
  148. NotificationManager notificationManager =
  149. (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  150. // Since android Oreo notification channel is needed.
  151. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  152. NotificationChannel channel = new NotificationChannel(channelId,
  153. "Channel human readable title",
  154. NotificationManager.IMPORTANCE_DEFAULT);
  155. notificationManager.createNotificationChannel(channel);
  156. }
  157. notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
  158. }
  159. //public static void sendNotificationToUser(String user, final String message) {
  160. // Firebase ref = new Firebase(FIREBASE_URL);
  161. // final Firebase notifications = ref.child("notificationRequests");
  162. //Map notification = new HashMap<>();
  163. // notification.put("username", user);
  164. // notification.put("message", message);
  165. // notifications.push().setValue(notification);
  166. //}
  167. @RequiresApi(api = Build.VERSION_CODES.O)
  168. private void setupChannels(NotificationManager notificationManager){
  169. CharSequence adminChannelName = "New notification";
  170. String adminChannelDescription = "Device to devie notification";
  171. NotificationChannel adminChannel;
  172. adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_HIGH);
  173. adminChannel.setDescription(adminChannelDescription);
  174. adminChannel.enableLights(true);
  175. adminChannel.setLightColor(Color.RED);
  176. adminChannel.enableVibration(true);
  177. if (notificationManager != null) {
  178. notificationManager.createNotificationChannel(adminChannel);
  179. }
  180. }
  181. }