Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class MyFirebaseMessagingService : FirebaseMessagingService() {
- private val ADMIN_CHANNEL_ID = "admin_channel"
- override fun onNewToken(p0: String) {
- super.onNewToken(p0)
- val firebaseUser = FirebaseAuth.getInstance().currentUser
- val refreshToken = FirebaseInstanceId.getInstance().token
- if (firebaseUser != null) {
- FirebaseDatabase.getInstance().getReference(USERS).child(
- FirebaseAuth.getInstance().currentUser!!.uid
- ).child(TOKEN).setValue(refreshToken)
- }
- }
- private fun scheduleJob() {
- // [START dispatch_job]
- val work: OneTimeWorkRequest = OneTimeWorkRequest.Builder(MyWorker::class.java).build()
- WorkManager.getInstance().beginWith(work).enqueue()
- // [END dispatch_job]
- }
- override fun onMessageReceived(remoteMessage: RemoteMessage) {
- val type = remoteMessage.data["type"]
- if (remoteMessage.data.isNotEmpty()) {
- Log.d("admin_channel", "Message data payload: " + remoteMessage.getData());
- scheduleJob()
- }
- var intent: Intent? = null
- if (type == "like") {
- intent = Intent(this, MainActivity::class.java)
- intent.putExtra("type", "like")
- } else if (type == "view"){
- intent = Intent(this, ProfileActivity::class.java)
- intent.putExtra("id", remoteMessage.data["id"])
- } else if (type == "message") {
- intent = Intent(this, ChatActivity::class.java)
- intent.putExtra("id", remoteMessage.data["id"])
- } else if (type == "gift") {
- intent = Intent(this, ProfileActivity::class.java)
- intent.putExtra("id", remoteMessage.data["id"])
- } else if (type == "kiss") {
- intent = Intent(this, ProfileActivity::class.java)
- intent.putExtra("id", remoteMessage.data["id"])
- } else {
- intent = Intent(this, MainActivity::class.java)
- }
- val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
- val notificationID = (0..10 * 1000 * 100).random()
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- setupChannels(notificationManager)
- }
- intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
- val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
- val largeIcon = getBitmapFromURL(remoteMessage.data["icon"])
- val notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
- val notificationBuilder =
- NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
- .setSmallIcon(R.drawable.ic_square_icon)
- .setLargeIcon(largeIcon)
- .setContentTitle(remoteMessage.data["title"])
- .setContentText(remoteMessage.data["message"])
- .setAutoCancel(true)
- .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
- .setSound(notificationSoundUri)
- .setContentIntent(pendingIntent)
- notificationBuilder.color = resources.getColor(R.color.purple)
- notificationManager.notify(notificationID, notificationBuilder.build())
- }
- @RequiresApi(api = Build.VERSION_CODES.O)
- private fun setupChannels(notificationManager: NotificationManager?) {
- val adminChannelName: CharSequence = "New notification"
- val adminChannelDescription = "Device to devie notification"
- val adminChannel: NotificationChannel
- adminChannel = NotificationChannel(
- ADMIN_CHANNEL_ID,
- adminChannelName,
- NotificationManager.IMPORTANCE_HIGH
- )
- adminChannel.description = adminChannelDescription
- adminChannel.enableLights(true)
- adminChannel.lightColor = Color.RED
- adminChannel.enableVibration(true)
- notificationManager?.createNotificationChannel(adminChannel)
- }
- fun getBitmapFromURL(src: String?): Bitmap? {
- return try {
- val url = URL(src)
- val connection = url.openConnection() as HttpURLConnection
- connection.doInput = true
- connection.connect()
- val input = connection.inputStream
- BitmapFactory.decodeStream(input)
- } catch (e: IOException) {
- // Log exception
- null
- }
- }
- companion object {
- private val FCM_API = "https://fcm.googleapis.com/fcm/send"
- private val contentType = "application/json"
- fun Context.sendNotification(
- title: String,
- message: String,
- type: String,
- receiver: String,
- icon: String
- ) {
- val notification = JSONObject()
- val notificationBody = JSONObject()
- try {
- notificationBody.put("title", title)
- notificationBody.put("message", message)
- notificationBody.put("type", type)
- notificationBody.put("icon", icon)
- notificationBody.put("id", FirebaseAuth.getInstance().currentUser!!.uid)
- notification.put("receiver", receiver)
- notification.put("data", notificationBody)
- } catch (e: JSONException) {
- }
- notification(notification)
- }
- private fun Context.notification(notification: JSONObject) {
- val jsonObjectRequest: JsonObjectRequest =
- object : JsonObjectRequest(FCM_API, notification,
- Response.Listener {
- Log.i("notification_send_app", "onSuccessResponse: ok!, ${it.toString()}")
- },
- Response.ErrorListener {
- Log.i(
- "notification_send_app",
- "onErrorResponse: Didn't work, error: ${it.message}, ${it.networkResponse.data}, ${it.networkResponse.statusCode}}"
- )
- }) {
- @Throws(AuthFailureError::class)
- override fun getHeaders(): Map<String, String> {
- val params: MutableMap<String, String> = HashMap()
- params["Authorization"] = serverKey
- params["Content-Type"] = contentType
- return params
- }
- }
- MySingleton.getInstance(applicationContext).addToRequestQueue(jsonObjectRequest)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment