Advertisement

Responsive Advertisement

Notification Code in kotlin updated with sound , vibrate and wake lock

  •  First of all you have to take permission at manifest 

    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

 

  • declare service
    <service
    android:name=".receiver.MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
    </service>
  • Take class of messagingservice
    
    
    class MyFirebaseMessagingService : FirebaseMessagingService() {

    private var wakeLock: PowerManager.WakeLock? = null

    override fun onNewToken(token: String) {
    super.onNewToken(token)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onMessageReceived(message: RemoteMessage) {
    super.onMessageReceived(message)
    val notificationData = message.data.let { data ->
    NotificationData(
    data["type"] ?: "default",
    data["title"] ?: "No Title",
    data["body"] ?: "No Body"
    )
    }
    Log.e(CommonUtils.TAG, "onMessageReceived: $notificationData")

    if (notificationData.type.isNotEmpty()) {
    createNotificationChannel(notificationData.type)
    createNotification(notificationData, applicationContext)
    }
    }

    private fun createNotificationChannel(channelId: String) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val name = "Channel ${
    channelId.replaceFirstChar {
    if (it.isLowerCase()) it.titlecase(Locale.ROOT) else it.toString()
    }
    }"
    val descriptionText = "Description for channel $channelId"
    val importance = NotificationManager.IMPORTANCE_HIGH
    val channel = NotificationChannel(channelId, name, importance).apply {
    description = descriptionText
    enableVibration(true)
    enableLights(true)
    lightColor = Color.GREEN
    lockscreenVisibility = Notification.VISIBILITY_PUBLIC
    }
    val notificationManager =
    getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    notificationManager.createNotificationChannel(channel)
    }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun createNotification(notificationData: NotificationData, context: Context) {
    val notificationIntent = Intent(context, HomeActivity::class.java).apply {
    flags = Intent.FLAG_ACTIVITY_FORWARD_RESULT or Intent.FLAG_ACTIVITY_CLEAR_TOP
    putExtra("type",notificationData.type)
    }
    val pendingIntent = PendingIntent.getActivity(
    context,
    0,
    notificationIntent,
    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
    )
    //val vibrationPattern = longArrayOf(0, 1000, 500, 1000) // Define your custom vibration pattern here

    // Acquire wake lock
    acquireWakeLock(context)
    val alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
    val notificationBuilder = NotificationCompat.Builder(context, notificationData.type)
    .setSmallIcon(R.drawable.logo1)
    .setContentTitle(notificationData.title)
    .setContentText(notificationData.body)
    .setLights(Color.GREEN, 1000, 300)
    .setPriority(NotificationCompat.PRIORITY_HIGH)
    .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.logo1))
    .setContentIntent(pendingIntent)
    .setAutoCancel(true)
    .setSound(alarmSound)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    notificationBuilder.setChannelId(notificationData.type)
    }

    val notification = notificationBuilder.build()

    val notificationManager =
    context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    notificationManager.notify(notificationData.type.hashCode(), notification)
    }

    private fun acquireWakeLock(context: Context) {
    val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
    wakeLock = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    powerManager.newWakeLock(
    PowerManager.FULL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.ON_AFTER_RELEASE,
    "MyApp::MyWakelockTag"
    )
    } else {
    powerManager.newWakeLock(
    PowerManager.PARTIAL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.ON_AFTER_RELEASE,
    "MyApp::MyWakelockTag"
    )
    }
    wakeLock?.acquire(10 * 1000L /*10 seconds*/)
    }

    override fun onDestroy() {
    super.onDestroy()
    // Release wake lock
    wakeLock?.release()
    }
    }
  • take permission of android 33 or 34+ versions

    private var permissionlauncher: ActivityResultLauncher<String>? = null
initRegisterLauncher()
private fun initRegisterLauncher() {
permissionlauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
if (!isGranted) {
CommonUtils.showAlertDialog(
requireContext(),
getString(R.string.permission_required_for_notification),
getString(R.string.ok)
) {
val intent = Intent().apply {
action = android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS
data = Uri.fromParts("package", requireActivity().packageName, null)
}
requireActivity().startActivity(intent)
}
}
}
}
private fun initPermissionCheck() {
if (Build.VERSION.SDK_INT >= 33) {
permissionlauncher?.let { launcher ->
if (ContextCompat.checkSelfPermission(
requireContext(),
android.Manifest.permission.POST_NOTIFICATIONS
)
!= PackageManager.PERMISSION_GRANTED
) {
launcher.launch(android.Manifest.permission.POST_NOTIFICATIONS)
} else {
loginRequest()
}
}
} else {
// Code to execute for SDK versions less than 34
loginRequest()
}
}

Post a Comment

0 Comments