developerandr

Notifications

May 9th, 2021
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.56 KB | None | 0 0
  1. class MyFirebaseMessagingService : FirebaseMessagingService() {
  2. private val ADMIN_CHANNEL_ID = "admin_channel"
  3.  
  4.  
  5. override fun onNewToken(p0: String) {
  6. super.onNewToken(p0)
  7. val firebaseUser = FirebaseAuth.getInstance().currentUser
  8. val refreshToken = FirebaseInstanceId.getInstance().token
  9. if (firebaseUser != null) {
  10. FirebaseDatabase.getInstance().getReference(USERS).child(
  11. FirebaseAuth.getInstance().currentUser!!.uid
  12. ).child(TOKEN).setValue(refreshToken)
  13. }
  14. }
  15. private fun scheduleJob() {
  16. // [START dispatch_job]
  17. val work: OneTimeWorkRequest = OneTimeWorkRequest.Builder(MyWorker::class.java).build()
  18. WorkManager.getInstance().beginWith(work).enqueue()
  19. // [END dispatch_job]
  20. }
  21. override fun onMessageReceived(remoteMessage: RemoteMessage) {
  22. val type = remoteMessage.data["type"]
  23. if (remoteMessage.data.isNotEmpty()) {
  24. Log.d("admin_channel", "Message data payload: " + remoteMessage.getData());
  25.  
  26. scheduleJob()
  27.  
  28. }
  29.  
  30.  
  31. var intent: Intent? = null
  32. if (type == "like") {
  33. intent = Intent(this, MainActivity::class.java)
  34. intent.putExtra("type", "like")
  35. } else if (type == "view"){
  36. intent = Intent(this, ProfileActivity::class.java)
  37. intent.putExtra("id", remoteMessage.data["id"])
  38. } else if (type == "message") {
  39. intent = Intent(this, ChatActivity::class.java)
  40. intent.putExtra("id", remoteMessage.data["id"])
  41. } else if (type == "gift") {
  42. intent = Intent(this, ProfileActivity::class.java)
  43. intent.putExtra("id", remoteMessage.data["id"])
  44. } else if (type == "kiss") {
  45. intent = Intent(this, ProfileActivity::class.java)
  46. intent.putExtra("id", remoteMessage.data["id"])
  47. } else {
  48. intent = Intent(this, MainActivity::class.java)
  49. }
  50.  
  51. val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
  52. val notificationID = (0..10 * 1000 * 100).random()
  53.  
  54. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  55. setupChannels(notificationManager)
  56. }
  57. intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
  58. val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
  59. val largeIcon = getBitmapFromURL(remoteMessage.data["icon"])
  60.  
  61. val notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
  62. val notificationBuilder =
  63. NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
  64. .setSmallIcon(R.drawable.ic_square_icon)
  65. .setLargeIcon(largeIcon)
  66. .setContentTitle(remoteMessage.data["title"])
  67. .setContentText(remoteMessage.data["message"])
  68. .setAutoCancel(true)
  69. .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
  70. .setSound(notificationSoundUri)
  71. .setContentIntent(pendingIntent)
  72.  
  73. notificationBuilder.color = resources.getColor(R.color.purple)
  74. notificationManager.notify(notificationID, notificationBuilder.build())
  75. }
  76.  
  77. @RequiresApi(api = Build.VERSION_CODES.O)
  78. private fun setupChannels(notificationManager: NotificationManager?) {
  79. val adminChannelName: CharSequence = "New notification"
  80. val adminChannelDescription = "Device to devie notification"
  81. val adminChannel: NotificationChannel
  82. adminChannel = NotificationChannel(
  83. ADMIN_CHANNEL_ID,
  84. adminChannelName,
  85. NotificationManager.IMPORTANCE_HIGH
  86. )
  87. adminChannel.description = adminChannelDescription
  88. adminChannel.enableLights(true)
  89. adminChannel.lightColor = Color.RED
  90. adminChannel.enableVibration(true)
  91. notificationManager?.createNotificationChannel(adminChannel)
  92. }
  93. fun getBitmapFromURL(src: String?): Bitmap? {
  94. return try {
  95. val url = URL(src)
  96. val connection = url.openConnection() as HttpURLConnection
  97. connection.doInput = true
  98. connection.connect()
  99. val input = connection.inputStream
  100. BitmapFactory.decodeStream(input)
  101. } catch (e: IOException) {
  102. // Log exception
  103. null
  104. }
  105. }
  106. companion object {
  107. private val FCM_API = "https://fcm.googleapis.com/fcm/send"
  108. private val contentType = "application/json"
  109. fun Context.sendNotification(
  110. title: String,
  111. message: String,
  112. type: String,
  113. receiver: String,
  114. icon: String
  115. ) {
  116.  
  117. val notification = JSONObject()
  118. val notificationBody = JSONObject()
  119. try {
  120. notificationBody.put("title", title)
  121. notificationBody.put("message", message)
  122. notificationBody.put("type", type)
  123. notificationBody.put("icon", icon)
  124. notificationBody.put("id", FirebaseAuth.getInstance().currentUser!!.uid)
  125. notification.put("receiver", receiver)
  126. notification.put("data", notificationBody)
  127. } catch (e: JSONException) {
  128. }
  129. notification(notification)
  130. }
  131.  
  132. private fun Context.notification(notification: JSONObject) {
  133. val jsonObjectRequest: JsonObjectRequest =
  134. object : JsonObjectRequest(FCM_API, notification,
  135. Response.Listener {
  136. Log.i("notification_send_app", "onSuccessResponse: ok!, ${it.toString()}")
  137. },
  138. Response.ErrorListener {
  139. Log.i(
  140. "notification_send_app",
  141. "onErrorResponse: Didn't work, error: ${it.message}, ${it.networkResponse.data}, ${it.networkResponse.statusCode}}"
  142. )
  143. }) {
  144. @Throws(AuthFailureError::class)
  145. override fun getHeaders(): Map<String, String> {
  146. val params: MutableMap<String, String> = HashMap()
  147. params["Authorization"] = serverKey
  148. params["Content-Type"] = contentType
  149. return params
  150. }
  151. }
  152. MySingleton.getInstance(applicationContext).addToRequestQueue(jsonObjectRequest)
  153. }
  154.  
  155. }
  156. }
Advertisement
Add Comment
Please, Sign In to add comment