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 9.9KB

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