push notification show incorrect time kotlin, sometimes not showing - android

i want to show push notification in kotlin at 7 AM & 16PM in here every 24Hours everyday. i make 2 broadcast receiver & 2 declare time inside oncreate, but sometimes push notification not show, i dont know if receiver blocked by miui saver
below my code AlarmBroadcastreceiver (for show 7 AM):
class AlarmBroadcastReceiver: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
showNotification(context)
}
internal fun showNotification(context: Context) {
val CHANNEL_ID = "1"// The id of the channel.
val name = context.getResources().getString(R.string.app_name)// The user-visible name of the channel.
val mBuilder: NotificationCompat.Builder
val intent = Intent()
val manufacturer = android.os.Build.MANUFACTURER
when(manufacturer) {
"xiaomi" ->
intent.component =
ComponentName(
"com.miui.securitycenter",
"com.miui.permcenter.autostart.AutoStartManagementActivity"
)
"oppo" ->
intent.component =
ComponentName(
"com.coloros.safecenter",
"com.coloros.safecenter.permission.startup.StartupAppListActivity"
)
"vivo" ->
intent.component =
ComponentName(
"com.vivo.permissionmanager",
"com.vivo.permissionmanager.activity.BgStartUpManagerActivity"
)
"samsung" ->
intent.component =
ComponentName(
"com.samsung.android.lool",
"com.samsung.android.sm.ui.battery.BatteryActivity"
)
"asus" ->
intent.component =
ComponentName(
"com.asus.mobilemanager",
"com.asus.mobilemanager.MainActivity"
)
}
val list = context.getPackageManager().queryIntentActivities(
intent,
PackageManager.MATCH_DEFAULT_ONLY
)
if (list.size > 0) {
context.startActivity(intent)
}
val notificationIntent = Intent(context, GreenHCMActivity::class.java)
val bundle = Bundle()
notificationIntent.putExtras(bundle)
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
//notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
//val contentIntent = PendingIntent.getActivity(
// context,
//1,
//notificationIntent,
//PendingIntent.FLAG_UPDATE_CURRENT
//)
var contentIntent = PendingIntent.getActivity(
context,
1,
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//mNotificationManager.cancel(1)
// mNotificationManager.cancelAll()
if (android.os.Build.VERSION.SDK_INT >= 26)
{
val mChannel = NotificationChannel(
CHANNEL_ID,
name,
NotificationManager.IMPORTANCE_HIGH
)
mNotificationManager.createNotificationChannel(mChannel)
mBuilder = NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setLights(Color.RED, 300, 300)
.setChannelId(CHANNEL_ID)
.setDefaults(DEFAULT_ALL)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000))
.setAutoCancel(true)
// Overrides ContentTitle in the big form of the template.
.setContentTitle("Selamat Pagi Jangan Lupa Untuk Absensi ")
.setContentIntent(contentIntent);
//.setContentTitle("Selamat Pagi Jangan Lupa Untuk Absensi ")
}
else
{
mBuilder = NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher_round)
//.setPriority(NotificationCompat.PRIORITY_MAX)
.setPriority(Notification.PRIORITY_HIGH)
//lollipop, marshmallow, nougat
.setContentTitle("Selamat Pagi Jangan Lupa Untuk Absensi ")
.setStyle(
NotificationCompat.BigPictureStyle()
// Provide the bitmap to be used as the payload for the BigPicture notification.
.bigPicture(
BitmapFactory.decodeResource(
context.resources,
R.drawable.absence
)
)
.setSummaryText("Mohon melakukan absensi pagi ini,Terima kasih")
// Override the large icon when the big notification is shown.
.bigLargeIcon(
BitmapFactory.decodeResource(
context.resources,
R.mipmap.ic_launcher_round
)
)
)
}
mBuilder.setContentIntent(contentIntent)
.setDefaults(DEFAULT_ALL)
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round)
val note = mBuilder.build()
mBuilder.setContentText("Mohon melakukan absensi pagi ini,Terima kasih")
.setStyle(
NotificationCompat.BigPictureStyle()
// Provide the bitmap to be used as the payload for the BigPicture notification.
.bigPicture(BitmapFactory.decodeResource(context.resources, R.drawable.absence))
// Override the large icon when the big notification is shown.
.bigLargeIcon(
BitmapFactory.decodeResource(
context.resources,
R.mipmap.ic_launcher_round
)
)
// Set the first line of text after the detail section in the big form of the template.
//.setSummaryText("Mohon melakukan absensi pagi ini,Terima kasih")
)
mNotificationManager.notify(1, mBuilder.build())
}
}
below my code Alarmbroadcastreceiver2 for show 16PM :
class AlarmBroadcastReceiver2: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
showNotification(context)
}
internal fun showNotification(context: Context) {
val CHANNEL_ID = "1"// The id of the channel.
val name = context.getResources().getString(R.string.app_name)// The user-visible name of the channel.
val mBuilder: NotificationCompat.Builder
val notificationIntent = Intent(context, GreenHCMActivity::class.java)
val bundle = Bundle()
notificationIntent.putExtras(bundle)
val intent = Intent()
val manufacturer = android.os.Build.MANUFACTURER
when(manufacturer) {
"xiaomi" ->
intent.component =
ComponentName(
"com.miui.securitycenter",
"com.miui.permcenter.autostart.AutoStartManagementActivity"
)
"oppo" ->
intent.component =
ComponentName(
"com.coloros.safecenter",
"com.coloros.safecenter.permission.startup.StartupAppListActivity"
)
"vivo" ->
intent.component =
ComponentName(
"com.vivo.permissionmanager",
"com.vivo.permissionmanager.activity.BgStartUpManagerActivity"
)
}
val list = context.getPackageManager().queryIntentActivities(
intent,
PackageManager.MATCH_DEFAULT_ONLY
)
if (list.size > 0) {
context.startActivity(intent)
}
//notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
//notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP )
//val contentIntent = PendingIntent.getActivity(
// context,
//1,
//notificationIntent,
//PendingIntent.FLAG_UPDATE_CURRENT
//)
val contentIntent = PendingIntent.getActivity(
context,
1,
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//mNotificationManager.cancel(2);
//mNotificationManager.cancelAll();
if (android.os.Build.VERSION.SDK_INT >= 26)
{
val mChannel = NotificationChannel(
CHANNEL_ID,
name,
NotificationManager.IMPORTANCE_HIGH,
)
mNotificationManager.createNotificationChannel(mChannel)
//mNotificationManager.cancel(1)
mBuilder = NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setLights(Color.RED, 300, 300)
.setChannelId(CHANNEL_ID)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setDefaults(DEFAULT_ALL)
.setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000))
.setAutoCancel(true)
.setContentTitle("Selamat Sore Jangan Lupa Untuk Absensi")
.setStyle(
NotificationCompat.BigPictureStyle()
// Provide the bitmap to be used as the payload for the BigPicture notification.
.bigPicture(
BitmapFactory.decodeResource(
context.resources,
R.drawable.absence2_2
)
)
// Override the large icon when the big notification is shown.
.bigLargeIcon(
BitmapFactory.decodeResource(
context.resources,
R.mipmap.ic_launcher_round
)
)
// Overrides ContentTitle in the big form of the template.
//.setBigContentTitle("Selamat Sore Jangan Lupa Untuk Absensi ")
// Set the first line of text after the detail section in the big form of the template.
//.setSummaryText("")
)
}
else
{
mBuilder = NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher_round)
//.setPriority(NotificationCompat.PRIORITY_MAX)
.setPriority(Notification.PRIORITY_HIGH)
//lollipop, marshmallow, nougat
.setContentTitle("Selamat Sore Jangan Lupa Untuk Absensi")
.setStyle(
NotificationCompat.BigPictureStyle()
// Provide the bitmap to be used as the payload for the BigPicture notification.
.bigPicture(
BitmapFactory.decodeResource(
context.resources,
R.drawable.absence2_2
)
)
.setSummaryText("Mohon melakukan absensi sore ini,Terima kasih")
// Override the large icon when the big notification is shown.
.bigLargeIcon(
BitmapFactory.decodeResource(
context.resources,
R.mipmap.ic_launcher_round
)
)
)
}
mBuilder.setContentIntent(contentIntent)
mBuilder.setContentText("Mohon melakukan absensi sore ini,Terima kasih")
.setDefaults(DEFAULT_ALL)
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round)
val note = mBuilder.build()
//mBuilder.setContentText("Yth Kepada Seluruh Karyawan dimohon untuk melakukan absensi di pagi ini,Terima Kasih")
mNotificationManager.notify(1, mBuilder.build())
//mNotificationManager.cancel(1)
}
}
below inside oncreate will call 2 different times:
//notif4 16.00 evening
val _intent2 = Intent(this, AlarmBroadcastReceiver2::class.java)
val pendingIntent2 = PendingIntent.getBroadcast(this, 1, _intent2, 0)
val alarmManager2 = this.getSystemService(Context.ALARM_SERVICE) as AlarmManager
//alarmManager2.cancel(pendingIntent2)
//val calendar2 = Calendar.getInstance()
val calendar2 = getInstance()
//calendar2.setTimeInMillis(System.currentTimeMillis())
calendar2.set(Calendar.HOUR_OF_DAY, 16)
calendar2.set(Calendar.MINUTE, 18)
calendar2.set(Calendar.SECOND, 0)
//calendar2.set(Calendar.AM_PM,Calendar.PM);
alarmManager2.setInexactRepeating( AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent2 )
//notif3 07:00 morning
val _intent = Intent(this, AlarmBroadcastReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(this, 2, _intent, 0)
val alarmManager = this.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(pendingIntent)
val calendar = getInstance()
//calendar.setTimeInMillis(System.currentTimeMillis())
calendar.set(Calendar.HOUR_OF_DAY, 7)
calendar.set(Calendar.MINUTE, 1)
calendar.set(Calendar.SECOND, 0)
//calendar.set(Calendar.AM_PM,Calendar.AM);
alarmManager.setInexactRepeating( AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent )
How To Resolve This? Hello I am nebie developer kotlin, I want to show push notification in kotlin at 7 AM & 16PM everyday, in here i make 2 broadcast receiver & 2 declare time inside oncreate, but sometimes push notification not show, i dont know if receiver blocked by miui saver, because sometimes show but wrong times.... I need more help to resolve , thank you very much.....

Related

How To Stop display push notification while open app in android?

package com.test.android
import android.app.*
import android.app.Notification.*
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat.getSystemService
import kotlinx.android.synthetic.main.fragment_profile.*
class AlarmBroadcastReceiver2: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
showNotification(context)
}
internal fun showNotification(context: Context) {
val CHANNEL_ID = "1"// The id of the channel.
val name = context.getResources().getString(R.string.app_name)// The user-visible name of the channel.
val mBuilder: NotificationCompat.Builder
val notificationIntent = Intent(context, MainActivity::class.java)
val bundle = Bundle()
notificationIntent.putExtras(bundle)
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP )
val contentIntent = PendingIntent.getActivity(
context,
1,
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (android.os.Build.VERSION.SDK_INT >= 26)
{
val mChannel = NotificationChannel(
CHANNEL_ID,
name,
NotificationManager.IMPORTANCE_HIGH
)
mNotificationManager.createNotificationChannel(mChannel)
mBuilder = NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setLights(Color.RED, 300, 300)
.setChannelId(CHANNEL_ID)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setDefaults(DEFAULT_ALL)
.setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000))
.setAutoCancel(true)
//.setContentTitle("Selamat Pagi Jangan Lupa Untuk Absensi ")
.setStyle(
NotificationCompat.BigPictureStyle()
// Provide the bitmap to be used as the payload for the BigPicture notification.
.bigPicture(
BitmapFactory.decodeResource(
context.resources,
R.drawable.absence2_2
)
)
// Override the large icon when the big notification is shown.
.bigLargeIcon(
BitmapFactory.decodeResource(
context.resources,
R.mipmap.ic_launcher_round
)
)
// Overrides ContentTitle in the big form of the template.
.setBigContentTitle("Selamat Sore Jangan Lupa Untuk Absensi ")
// Set the first line of text after the detail section in the big form of the template.
.setSummaryText("Mohon melakukan absensi sore ini,Terima kasih")
)
}
else
{
mBuilder = NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher_round)
//.setPriority(NotificationCompat.PRIORITY_MAX)
.setPriority(Notification.PRIORITY_HIGH)
.setContentTitle("Title")
}
mBuilder.setContentIntent(contentIntent)
.setDefaults(DEFAULT_ALL)
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round)
val note = mBuilder.build()
//mBuilder.setContentText("Yth Kepada Seluruh Karyawan dimohon untuk melakukan absensi di pagi ini,Terima Kasih")
mBuilder.setAutoCancel(true)
mNotificationManager.notify(1, mBuilder.build())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round)
} else {
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round)
}
}
}
//notif4 16.00 evening
val _intent2 = Intent(this, AlarmBroadcastReceiver2::class.java)
val pendingIntent2 = PendingIntent.getBroadcast(this, 0, _intent2, 0)
val alarmManager2 = this.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager2.cancel(pendingIntent2)
val calendar2 = Calendar.getInstance()
calendar2.setTimeInMillis(System.currentTimeMillis())
calendar2.set(Calendar.HOUR_OF_DAY, 16)
calendar2.set(Calendar.MINUTE, 0)
calendar2.set(Calendar.SECOND, 0)
//alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis() /1000, AlarmManager.INTERVAL_DAY, pendingIntent2)
//alarmManager2.setExact(AlarmManager.RTC_WAKEUP,calendar2.getTimeInMillis()/1000 , pendingIntent2)
//alarmManager2.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar2.getTimeInMillis()/1000 ,AlarmManager.INTERVAL_DAY , pendingIntent2)
alarmManager2.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar2.getTimeInMillis() ,AlarmManager.INTERVAL_DAY , pendingIntent2)
I'm new to android development... trying to build application which send notification at specific time daily.First time if I tap on notification it opens application and notification doesn't come again. But after that if I open application it shows notification again.. how to stop showing it again? but show only at particular time?

How to stop getting notification on every launch of application in kotlin?

package com.greenhcm.android
import android.app.*
import android.app.Notification.*
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import androidx.core.app.NotificationCompat
import kotlinx.android.synthetic.main.fragment_profile.*
class AlarmBroadcastReceiver: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
showNotification(context)
}
internal fun showNotification(context: Context) {
val CHANNEL_ID = "1"// The id of the channel.
val name = context.getResources().getString(R.string.app_name)// The user-visible name of the channel.
val mBuilder: NotificationCompat.Builder
val intent = Intent()
val manufacturer = android.os.Build.MANUFACTURER
when(manufacturer) {
"xiaomi" ->
intent.component=
ComponentName("com.miui.securitycenter",
"com.miui.permcenter.autostart.AutoStartManagementActivity")
"oppo" ->
intent.component =
ComponentName("com.coloros.safecenter",
"com.coloros.safecenter.permission.startup.StartupAppListActivity")
"vivo" ->
intent.component =
ComponentName("com.vivo.permissionmanager",
"com.vivo.permissionmanager.activity.BgStartUpManagerActivity")
"samsung" ->
intent.component =
ComponentName(
"com.samsung.android.lool",
"com.samsung.android.sm.ui.battery.BatteryActivity")
"asus" ->
intent.component =
ComponentName(
"com.asus.mobilemanager",
"com.asus.mobilemanager.MainActivity"
)
}
val list = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
if (list.size > 0) {
context.startActivity(intent)
}
val notificationIntent = Intent(context, GreenHCMActivity::class.java)
val bundle = Bundle()
notificationIntent.putExtras(bundle)
//notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK)
//val contentIntent = PendingIntent.getActivity(
// context,
//1,
//notificationIntent,
//PendingIntent.FLAG_UPDATE_CURRENT
//)
var contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//mNotificationManager.cancel(1)
mNotificationManager.cancelAll()
if (android.os.Build.VERSION.SDK_INT >= 26)
{
val mChannel = NotificationChannel(
CHANNEL_ID,
name,
NotificationManager.IMPORTANCE_HIGH
)
mNotificationManager.createNotificationChannel(mChannel)
mBuilder = NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setLights(Color.RED, 300, 300)
.setChannelId(CHANNEL_ID)
.setDefaults(DEFAULT_ALL)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000))
.setAutoCancel(true)
// Overrides ContentTitle in the big form of the template.
.setContentTitle("Selamat Pagi Jangan Lupa Untuk Absensi ")
.setContentIntent(contentIntent);
//.setContentTitle("Selamat Pagi Jangan Lupa Untuk Absensi ")
}
else
{
mBuilder = NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setPriority(Notification.PRIORITY_HIGH)
//.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentTitle("Title")
}
mBuilder.setContentIntent(contentIntent)
.setDefaults(DEFAULT_ALL)
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round)
val note = mBuilder.build()
mBuilder.setContentText("Mohon melakukan absensi pagi ini,Terima kasih")
.setStyle(
NotificationCompat.BigPictureStyle()
// Provide the bitmap to be used as the payload for the BigPicture notification.
.bigPicture(BitmapFactory.decodeResource(context.resources, R.drawable.absence))
// Override the large icon when the big notification is shown.
.bigLargeIcon(
BitmapFactory.decodeResource(
context.resources,
R.mipmap.ic_launcher_round
)
)
// Set the first line of text after the detail section in the big form of the template.
//.setSummaryText("Mohon melakukan absensi pagi ini,Terima kasih")
)
mNotificationManager.notify(1, mBuilder.build())
}
}
Above My Receiver like this,
Below in oncreate activity
val _intent = Intent(this, AlarmBroadcastReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(this, 1, _intent, 0)
val alarmManager = this.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val calendar = Calendar.getInstance()
calendar.setTimeInMillis(System.currentTimeMillis())
calendar.set(Calendar.HOUR_OF_DAY, 7)
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.AM_PM,Calendar.AM);
//alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() , 24*60*60*1000, pendingIntent)
//alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()/1000 ,AlarmManager.INTERVAL_DAY, pendingIntent)
//alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()/1000 ,AlarmManager.INTERVAL_DAY, pendingIntent)
//alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis()/1000 ,AlarmManager.INTERVAL_DAY , pendingIntent)
//alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent)
alarmManager.cancel(pendingIntent)
alarmManager.setInexactRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY,
pendingIntent
)
I'm new to android development... trying to build application which send notification at specific time daily. But after that if I open application it shows notification every time on launch.. how to stop showing it again? please help me thank you
Iqbal,
you are sending an Alarm on
calendar.getTimeInMillis(),
It will return your current time in milliseconds. Hence alarm whenever you run on create. i.e. whenever you open the app. try different times. Or add 1000 * 60 * (min) in millis.

WorkManager and notification not working on firsttime

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)
}

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)
}
}

Prevent old notifications from firing

I'm making an app that i schedule notifications for a day say morning , evening and night - the problem is if i opened the app at night the old notifications of morning and evening shows . i use below code
val alarmMgr = MyApplication.appContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager?
val intent = Intent(MyApplication.appContext, MyAlarmReceiver::class.java)
intent.putExtra("Title",title)
intent.putExtra("Body",body)
intent.putExtra("Id",id)
intent.putExtra("Sound",sound)
val pendingIntent = PendingIntent.getBroadcast(MyApplication.appContext, id, intent, 0)
alarmMgr!!.setRepeating(AlarmManager.RTC_WAKEUP,time,AlarmManager.INTERVAL_DAY,pendingIntent)
With this part inside onReceive of alarm
private fun sendNotification( intent: Intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationID = intent.extras!!.getInt("Id")!!
val title = intent.extras!!.getString("Title")
val body = intent.extras!!.getString("Body")
val sound = intent.extras!!.getString("Sound")
val channelID = "com.ebookfrenzy.notifydemo.news"
val resultIntent = Intent(MyApplication.appContext, MainActivity::class.java)
resultIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
val pendingIntent = PendingIntent.getActivity(
MyApplication.appContext,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT)
val notification = Notification.Builder(MyApplication.appContext,
channelID)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setChannelId(channelID)
.setContentIntent(pendingIntent)
.build()
sound?.let {
notification.sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + MyApplication.appContext.getPackageName() + "/raw/$it")
}
var notificationManager = MyApplication.appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager?.notify(notificationID, notification)
} else {
}
}

Categories

Resources