Android custom notification sound not working on some device - android

I have set custom sound for notification. It's working for some device but not working on some device mostly Xiaomi device.
I have used this code:
private fun createNotificationChannel(){
val context = AppApplication.getContext()
val notificationManagerCompat = NotificationManagerCompat.from(context)
preChannelIds.forEach {
deleteChannel(notificationManagerCompat,it)
}
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val attributes = getAudioAttributes()
val soundUri = getSoundUri(context)
val importance = NotificationManagerCompat.IMPORTANCE_HIGH
val channelBuilder = NotificationChannelCompat.Builder(channelId, importance).apply {
setName(channelName)
setDescription(channelDescription)
setSound(soundUri, attributes)
setVibrationPattern(vibrationPattern)
setLightsEnabled(true)
setShowBadge(true)
}
val channel = channelBuilder.build()
notificationManagerCompat.createNotificationChannel(channel)
}
}
fun sendNotification(title:String, message:String){
val context = AppApplication.getContext()
val intent = ....
val notificationManagerCompat = NotificationManagerCompat.from(AppApplication.getContext())
val pendingIntent = PendingIntent.getActivity(
AppApplication.getContext(), notificationRequestCode, intent,
PendingIntent.FLAG_UPDATE_CURRENT)
val notificationBuilder = NotificationCompat.Builder(AppApplication.getContext(), channelId)
.setSmallIcon(getNotificationIcon())
.setContentTitle(title)
.setContentText(message)
.setStyle(NotificationCompat.BigTextStyle().bigText(message))
.setAutoCancel(true)
.setVibrate(vibrationPattern)
.setColor(ContextCompat.getColor(AppApplication.getContext(), R.color.colorPrimary))
.setContentIntent(pendingIntent)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
notificationBuilder.priority = NotificationCompat.PRIORITY_MAX
notificationBuilder.setSound(getSoundUri(context))
}
val notification = notificationBuilder.build()
notification.flags = Notification.FLAG_INSISTENT
notificationManagerCompat.notify(notificationRequestCode, notification)
}
Please help me to solve this issue for some device. Is there any other solution for this issue.

Related

How to make Android Notifications even when the app is closed like any chat app

I want to make Android Notifications to show even when the app is closed like any chat app
i tried using this->
fun createnotfictionchannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Title"
val desc = "desc"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("id", name, importance).apply {
description = desc
}
val notificationManager : NotificationManager? = requireActivity().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
notificationManager!!.createNotificationChannel(channel)
}
}
fun sendNote(title:String, description:String){
val pendingIntent: PendingIntent =
Intent(requireContext(), MainActivity::class.java).let { notificationIntent ->
PendingIntent.getActivity(requireContext(), 0, notificationIntent,
PendingIntent.FLAG_IMMUTABLE)
}
val builder =
NotificationCompat.Builder(requireContext())
.setSmallIcon(R.drawable.ic_baseline_notifications_24)
.setContentTitle(title)
.setContentText(description)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setCategory(Notification.CATEGORY_MESSAGE)
.setAutoCancel(true)
with(NotificationManagerCompat.from(requireContext())){
notify(1, builder.build())
}
}
But once the app is closed there isn't any notifications,
What can i use that has as little code possible?
Thanks

Firebase Cloud Messaging received BUT doesn't Popup!!! - KOTLIN

This is my code!
I'm building an application that receives notifications from firebase.
The App receiving the notification but doesn't popup it.
Any Help!
class MyFirebaseMessagingService : FirebaseMessagingService() {
val TAG = "FirebaseMessagingService"
override fun onMessageReceived(p0: RemoteMessage) {
super.onMessageReceived(p0)
Log.d(TAG, "{$p0}")
if (p0.notification !=null){
showNotification(p0.notification?.title, p0.notification?.body)
}
}
private fun showNotification(title: String?, body: String?){
val intent=Intent(applicationContext, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent=PendingIntent.getActivities(
this,
0,
arrayOf(intent),
PendingIntent.FLAG_UPDATE_CURRENT
)
//val soundUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_logo_border)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(2)
val notificationManager=getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notificationBuilder.build())
}
override fun onNewToken(token: String) {
super.onNewToken(token)
Log.d(TAG, "Refreshed token: $token")
}
I think it's because of the notification channel which came out with Android 8.0.
Call this function before building your notification.
private fun createNotificationChannel(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val existingChannel = notificationManager.getNotificationChannel(CHANNEL_ID)
if (existingChannel == null) {
// Create the NotificationChannel
val name = context.getString(R.string.defaultChannel)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val mChannel = NotificationChannel(CHANNEL_ID, name, importance)
mChannel.description = context.getString(R.string.notificationDescription)
notificationManager.createNotificationChannel(mChannel)
}
}
}
And use this with your code
NotificationManagerCompat.from(context).apply {
cancelAll() // Remove prior notifications; only allow one at a time.
notify(1 or your notification id, notificationBuilder.build())
}
instead of
val notificationManager=getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notificationBuilder.build())
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification_icon)
.setTicker(title)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(pendingIntent)
.setStyle(NotificationCompat.BigTextStyle().bigText(message))
.setSound(defaultSoundUri)
.setContentText(message)
if (bitmap != null) {
notificationBuilder.setLargeIcon(bitmap)
}
val notificationManager = applicationContext.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(channelId,
channelName,
NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(notificationId, notificationBuilder.build())

How to open app when notification is clicked in android?

I already made a notification without intent to MainActivity and it works fine, but when I add that intent to my MainActivity the notification does not show anymore. Is there anything wrong with my code or do I need to change the manifest or add some code in my MainActivity?
Here is my code. I set it into two functions - setDailyReminder and showAlarmNotification.
fun setDailyReminder(context: Context, type: String, message: String) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, MainActivity::class.java)
intent.putExtra(EXTRA_MESSAGE, message)
intent.putExtra(EXTRA_TYPE, type)
val timeArray =
TIME_DAILY.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeArray[0]))
calendar.set(Calendar.MINUTE, Integer.parseInt(timeArray[1]))
calendar.set(Calendar.SECOND, 0)
val pendingIntent = PendingIntent.getBroadcast(context,
ID_DAILY, intent, 0)
alarmManager.setInexactRepeating(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
AlarmManager.INTERVAL_DAY,
pendingIntent
)
Toast.makeText(context, "Daily reminder set up", Toast.LENGTH_SHORT).show()
}
private fun showAlarmNotification(
context: Context,
title: String,
message: String?,
notifId: Int
) {
val CHANNEL_ID = "Github App"
val CHANNEL_NAME = "Let's find favourite user on Github"
val notificationManagerCompat =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_play_circle_filled_white_24dp)
.setContentTitle(title)
.setContentText(message)
.setSound(alarmSound)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT
)
builder.setChannelId(CHANNEL_ID)
notificationManagerCompat.createNotificationChannel(channel)
}
val notification = builder.build()
notification.flags = notification.flags or Notification.FLAG_AUTO_CANCEL
notificationManagerCompat.notify(notifId, notification)
}
fun showNotification(context: Context,title: String, message:String, notifId: Int){
createNotificationChannel(context)
val intent = Intent(context, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0,
intent,PendingIntent.FLAG_ONE_SHOT)
var builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_play_circle_filled_white_24dp)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setColor(resources.getColor(R.color.colorAccent))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
val notificationManagerCompat = NotificationManagerCompat.from(this)
notificationManagerCompat.notify(notifId, builder.build())
}
private fun createNotificationChannel(context: Context) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Test"
val descriptionText = "FCM"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}

Custom notification is not creating when I add custom layout

I have to create a custom notification like what's app calling notification. Notification does not create if I add my custom layout to the NotificationCompat Builder. Below is my code to create notification.
Creating Notification
context?.let {
val notificationLayout = RemoteViews(it.packageName, R.layout.custom_notification_collapsed)
val notificationLayoutExpanded = RemoteViews(it.packageName, R.layout.custom_notification)
notificationLayout.setImageViewResource(R.id.iv_icon, R.drawable.icon)
notificationLayout.setTextViewText(R.id.tv_app_name, it.getString(R.string.app_name))
notificationLayout.setTextViewText(R.id.time_stamp, it.getString(R.string.just_now))
notificationLayoutExpanded.setImageViewResource(R.id.iv_icon,R.drawable.icon)
notificationLayoutExpanded.setTextViewText(R.id.tv_app_name, it.getString(R.string.app_name))
notificationLayoutExpanded.setTextViewText(R.id.content, it.getString(R.string.text))
notificationLayout.setTextViewText(R.id.time_stamp, it.getString(R.string.just_now))
var builder = NotificationCompat.Builder(it, AppConstants.CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setTicker("Noification is created")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCustomContentView(notificationLayout)
.setCustomBigContentView(notificationLayoutExpanded)
var customNotificationCompat: NotificationManagerCompat = NotificationManagerCompat.from(it)
customNotificationCompat.notify(0, builder.build())
}
Creating Channel and calling it from Application class:
fun createNotificationChannel(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = context.getString(R.string.app_name)
val descriptionText = context.getString(R.string.text)
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(AppConstants.CHANNEL_ID, name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}

Custom notification tone is not playing on emulator

I am setting a custom tone for notifications. The notification is received via Firebase messaging data payload. The message is displayed correctly but the custom tone is not played. What is the problem? Here is the code
override fun onMessageReceived(remoteMessage: RemoteMessage) {
val sound = Uri.parse("android.resource://" + applicationContext.packageName +"/"+R.raw.tone)
if (remoteMessage.data.isNotEmpty()) {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
val channelId = "Default"
val builder = NotificationCompat.Builder(this, channelId)
.setLargeIcon(BitmapFactory.decodeResource(resources,R.drawable.ic_logo))
.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(remoteMessage.data["title"]).setVisibility(VISIBILITY_PRIVATE)
.setSound(sound)
.setContentText(remoteMessage.data["body"]).setAutoCancel(true).setContentIntent(pendingIntent).setPriority(NotificationManager.IMPORTANCE_MAX)
val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
val attributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
val channel = NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_HIGH)
manager.createNotificationChannel(channel)
channel.setSound(sound, attributes)
}
manager.notify(0, builder.build())
}
}

Categories

Resources