WorkManager with notification not working on firsttime. But working when I open app, after that the notification will work normally.
WorkManager.getInstance(requireContext()).beginWith(listOfWork).enqueue()
if (workNumber == "1" && stateToAlert1) {
val strText= settingSharedPreferences1.getString("strText", null)
val builder = buildNotification(context, "1", strText)
registerChannel(context, strText, "1")
with(NotificationManagerCompat.from(context)) {
notify(1, builder.build())
}
}
private fun buildNotification(context: Context, channelId: String,textToAlert: String?): NotificationCompat.Builder {
val intent = Intent(context, MainActivity::class.java)
intent.putExtra("score", Random.nextInt(5, 30))
intent.putExtra("channelId", channelId)
val pendingIntent: PendingIntent = PendingIntent.getActivity(context, channelId.toInt(), intent, 0)
return NotificationCompat.Builder(context, channelId)
.setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
.setContentTitle("Notification")
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentText(textToAlert)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setAutoCancel(false)
}
Related
I have implemented a broadcast receiver to ask the user to restart the app if it is killed. I have confirmed that the broadcast receiver is being called fine, and it runs the below line but for some reason, I am not getting any notification.
Here is the code,
class ForegroundLocationServicesRestarter : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (intent != null) {
if (intent.action != ForegroundLocationService.ACTION_RESTART_LOCATION_UPDATES) {
return
}
}
val notificationChannelId = "restartDeliveryApp"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(notificationChannelId, "location_notif_chan", NotificationManager.IMPORTANCE_MAX)
val manager = context.getSystemService(LifecycleService.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(notificationChannel)
}
val fullScreenIntent = Intent(context, DeliveryManActivity::class.java)
fullScreenIntent.putExtra("RESTART_TRIGGERED", true)
val fullScreenPendingIntent = PendingIntent.getActivity(
context, 0,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT
)
NotificationCompat.Builder(context, notificationChannelId)
.setSmallIcon(R.drawable.ic_truck_red)
.setContentTitle(context.getString(R.string.restarter_title))
.setContentText(context.getString(R.string.restarter_message))
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setFullScreenIntent(fullScreenPendingIntent, true)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.build()
}
}
The notification channel is unique, the app has notification permission and also, full intent permission in the manifest. Any help is highly appreciated.
Plus there is already one service notification, does that impact this in any way?
was not pushing notifications into the system to display! Just need to do this!
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(notificationChannelId, "location_notif_chan", NotificationManager.IMPORTANCE_MAX)
val manager = context.getSystemService(LifecycleService.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(notificationChannel)
}
val dmIntent = Intent(context, DeliveryManActivity::class.java)
dmIntent.putExtra("RESTART_TRIGGERED", true)
val dmPendingIntent = PendingIntent.getActivity(
context, 0, dmIntent, PendingIntent.FLAG_UPDATE_CURRENT
)
// Prepare a notification with vibration, sound and lights
val builder = NotificationCompat.Builder(context, notificationChannelId)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_truck_red)
.setContentTitle(context.getString(R.string.restarter_title))
.setContentText(context.getString(R.string.restarter_message))
.setLights(Color.RED, 1000, 1000)
.setVibrate(longArrayOf(0, 400, 250, 400))
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(dmPendingIntent)
Pushy.setNotificationChannel(builder, context)
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(7, builder.build()) // same notification id to override
I am implementing FCM in my app. I want my device to vibrate and blink led on receiving notification. But it seems to not work as i expected. Is there any way to achieve this with FCM. Here's my code:
private fun sendNotification(messageBody: String?) {
val intent = Intent(this, HomeActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(
this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
val channelId = "my_channel_id"
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(applicationContext, channelId)
.setAutoCancel(true)
.setSmallIcon(R.drawable.splash_icon)
.setContentText(body)
.setContentTitle(title)
.setContentIntent(pendingIntent)
.setSound(defaultSoundUri)
.setVibrate(longArrayOf(1000, 1000, 1000, 1000))
.setLights(0, 2000, 500)
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel =
NotificationChannel(channelId, "app", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0, notificationBuilder.build())
}
I try to create a notification with notificationBuilder and notificationManager. Everything seems all right but the notification does not appear when the app is in the background nor when it is in the foreground.
Can you help? Here is the code so far:
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.i("info", "Message received: ${remoteMessage.from}")
Log.i("info", remoteMessage.data.toString())
if (remoteMessage.data != null) {
showNotification(remoteMessage.data.get("title"), remoteMessage.data.get("text"))
}
}
private fun showNotification(title: String?, body: String?) {
Log.i("info", "show notification $title $body")
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this)
.setContentText(body)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
}
}
I'm using Kotlin and Android Studio to try and push a Notification in a test app. I followed the instructions in the Android Developers site on How to create a Notification (https://developer.android.com/training/notify-user/build-notification) but I seem to be doing something wrong as my Notification is not showing anywhere. Here's my code:
val intent = Intent(context, Profile::class.java)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0);
val builder = NotificationCompat.Builder(this.context)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_MAX)
builder.setContentIntent(pendingIntent).setAutoCancel(true)
val mNotificationManager = message.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
with(mNotificationManager) {
notify(123, builder.build())
I really don't know what I'm missing so I would be grateful for any help.
According to your code, you are not creating a Notification channel.
Notification channel is necessary from Android Oreo and above
So if you are running the app Android O and above devices without a notification channel, your notification won't show up.
Create Notification Channel
fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "all_notifications" // You should create a String resource for this instead of storing in a variable
val mChannel = NotificationChannel(
channelId,
"General Notifications",
NotificationManager.IMPORTANCE_DEFAULT
)
mChannel.description = "This is default channel used for all other notifications"
val notificationManager =
mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
}
}
Then create a notification using the same channelId while creating a notification.
createNotificationChannel()
val channelId = "all_notifications" // Use same Channel ID
val intent = Intent(context, Profile::class.java)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0);
val builder = NotificationCompat.Builder(this.context, channelId) // Create notification with channel Id
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_MAX)
builder.setContentIntent(pendingIntent).setAutoCancel(true)
val mNotificationManager =
message.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
with(mNotificationManager) {
notify(123, builder.build())
Hope it helps.
try something like
val intent = Intent(context, Profile::class.java)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0)
val mNotificationManager =
message.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//Don't forget this check
val channel = NotificationChannel (
channelId,
"my_notification",
NotificationManager.IMPORTANCE_HIGH
)
channel.enableLights(true)
channel.lightColor = Color.GREEN
channel.enableVibration(false)
val builder = NotificationCompat.Builder(this.context, "channel_id")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_MAX)
builder.setContentIntent(pendingIntent).setAutoCancel(true)
mNotificationManager.createNotificationChannel(channel)//Notice this
mNotificationManager.notify(123, builder.build())
}
else {
//Create Notifcation for below Oreo
}
Does your Logcat say something like:
E/NotificationManager: notifyAsUser: tag=null, id=123, user=UserHandle{0}
Also have a look at your line:
val intent = Intent(context, Profile::class.java)
IF all else fails create a test Actvity with hello world.
And then make the line look like:
val intent = Intent(context, testActivity::class.java)
Remember to add the activity to your Manifest
The following line
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0);
should not have a semi colon. Kotin doesn't need this.
Is Profile your Class or System Class?
Try out this method and you can pass message and title dynamically :
private fun showNotification(title: String?, body: String?) {
val intent = Intent(this, Profile::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT)
val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notificationBuilder.build())
}
I Have problem with my notification.
First way - I open my app, then I push notification from FCM first time, I click the notif, my code executed, I push again for second time, I click my notif, my code still execute, I try more more time is worked well.
Second way - My app still close, I push notif from FCM first time, then I Click the notif, so my app will open and my code executed, then I push notif again for second time, my code NOT executed, I try more more time still NOT working.
until I swipe my app, and try again, the problem still happen.
this is my code
class MyFirebaseMessagingService : FirebaseMessagingService() {
var userInformation = AccountTableDao()
val sp: SharedPreferences by lazy { SharedPreference.instance }
val gad: GetAccountData by lazy { AccountDatabase.instance }
override fun onNewToken(token: String) {
super.onNewToken(token)
Log.d("firebase", "INSTANCE ID ===> $token")
}
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
remoteMessage?.let {
sendNotification(it.data)
}
}
private fun sendNotification(messageData: Map<String, String>) {
var status = messageData.get("status")
val uuid = messageData.get("uuid")
val restaurantId = messageData.get("restaurantId")
val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val titleText = messageData.get("title").toString()
val contentText = messageData.get("body").toString()
val intent = Intent(applicationContext, RestaurantMenuActivity::class.java)
intent.putExtra(Argument.NOTIF_UUID, uuid)
intent.putExtra(Argument.NOTIF_RESTAURANT_ID, restaurantId)
intent.putExtra(Argument.NOTIF_STATUS, status)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val pendingIntent = PendingIntent.getActivity(applicationContext,System.currentTimeMillis().toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val notificationChannel = NotificationChannel("appety", "appety_notification", NotificationManager.IMPORTANCE_HIGH)
notificationManager .createNotificationChannel(notificationChannel)
notificationManager.notify(System.currentTimeMillis().toInt(), NotificationCompat.Builder(this, "1")
.setChannelId(System.currentTimeMillis().toString())
.setContentTitle(titleText)
.setStyle(NotificationCompat.BigTextStyle().bigText(contentText))
.setContentText(contentText)
.setSmallIcon(R.drawable.ic_check_black_24dp)
.setLargeIcon( BitmapFactory.decodeResource(applicationContext.resources, R.drawable.logo_appety))
.setContentIntent(pendingIntent)
.setOngoing(false)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setColor(ContextCompat.getColor(applicationContext, R.color.colorBonAppety))
.build())
}
else{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationManager .notify(System.currentTimeMillis().toInt(), NotificationCompat.Builder(this, System.currentTimeMillis().toString())
.setContentTitle(titleText)
.setStyle (NotificationCompat.BigTextStyle().bigText(contentText))
.setContentText(contentText)
.setSmallIcon(R.drawable.ic_check_black_24dp)
.setLargeIcon( BitmapFactory.decodeResource(applicationContext.resources, R.drawable.logo_appety))
.setContentIntent(pendingIntent)
.setOngoing(false)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setColor(ContextCompat.getColor(applicationContext, R.color.colorBonAppety))
.build())
} else {
notificationManager .notify(System.currentTimeMillis().toInt(), NotificationCompat.Builder(this, "1")
.setContentTitle(titleText)
.setStyle (NotificationCompat.BigTextStyle().bigText(contentText))
.setContentText(contentText)
.setContentIntent(pendingIntent)
.setOngoing(false)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.build())
}
}
}
companion object {
private val TAG = "token"
}
}
and manifest
<service
android:name=".service.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Why Pending Intent not working and how to fix that.
Sorry for my english and regard.
You should try setAutoCancel() method when creating the notification.
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder summary = new NotificationCompat.Builder(this);
summary.setAutoCancel(true);
And if you passing an intent to the notification, then use this
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent resultIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);