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?
Related
I have two forground service FS1 and FS2 , with each one i create notification , if FS1 is running and i start FS2 the old notification get replaced , i want both to stay ,
this is how i create notification
private fun createNotification(): Notification {
val notificationChannelId = "123"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(
notificationChannelId,
"Notification service channel",
NotificationManager.IMPORTANCE_HIGH
).let {
it.description = "Notification Service channel"
it.enableLights(true)
it.lightColor = Color.RED
it.enableVibration(true)
it.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
it
}
notificationManager.createNotificationChannel(channel)
}
val pendingIntent: PendingIntent = Intent(this, MainActivity::class.java).let { notificationIntent ->
PendingIntent.getActivity(this, 0, notificationIntent, 0)
}
val builder: Notification.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Notification.Builder(
this,
notificationChannelId
) else Notification.Builder(this)
return builder
.setContentTitle("title")
.setContentText("Content")
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.notification_icon)
.setTicker("Ticker text")
.setPriority(Notification.PRIORITY_HIGH)
.build()
}
and in the onCreate methode
val notification = createNotification()
startForeground(1, notification)
and in the other service i create notification with the same way !
Ok my bad , i found out why , at onCreate methode , in both services i was using id 1 , i should use different id
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.....
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.
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)
}
}
I am using the following to present notifications to users on Android which currently works fine but I am having an issue that the notification appears in the status bar but does not come up as a heads up like a Facebook or WhatsApp notification does on the device? I get the notification but have to pull down on the status bar to view it. I am wondering is there a way to make this appear on the top of the screen in bubble format or is this something that varies between phone settings?
Code is attached below:
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addNotification(10,"eventname","roomname");
addNotification(25,"eventname2","roomname2");
}
public void addNotification(int test, String test2, String test3){
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("test",test2);
intent.putExtra("test2",test3);
final int _id = 50;
Random random = new Random();
final int randomInt = random.nextInt();
System.out.println("random integer:" + randomInt);
PendingIntent appIntent = PendingIntent.getBroadcast(this, randomInt, intent,PendingIntent.FLAG_UPDATE_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, test);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), appIntent);
}
}
AlarmReceiver
public class AlarmReceiver extends BroadcastReceiver{
private static final String CHANNEL_ID = "com.singhajit.notificationDemo.channelId";
#Override
public void onReceive(Context context, Intent intent) {
Intent notificationIntent = new Intent(context, NotificationActivity.class);
String passed = intent.getStringExtra("test");
String passed2 = intent.getStringExtra("test2");
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(NotificationActivity.class);
stackBuilder.addNextIntent(notificationIntent);
String messageBody = "Your event " + passed + " is about to start in 15 minutes, in room "+passed2;
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(context);
builder.setStyle(new Notification.BigTextStyle(builder)
.bigText(messageBody)
.setBigContentTitle("UA Reloaded Event Starting")
.setSummaryText("Tap To View Info"))
.setContentText(messageBody)
.setSmallIcon(R.drawable.ic_launcher)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setPriority(Notification.PRIORITY_MAX);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId(CHANNEL_ID);
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String name = "NotificationDemo";
String description = "NotificationDemo";
int importance = NotificationManager.IMPORTANCE_HIGH; //Important for heads-up notification
NotificationChannel channel = new NotificationChannel("1", name, importance);
channel.setDescription(description);
channel.setShowBadge(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
// NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, builder.build());
}
}
If you still need an answer or for anyone else in order to show the notification as heads-up you have to add your channel id to the Builder.
.setChannelId(CHANNEL_ID)
like so:
val notification = NotificationCompat.Builder(getContext(), CHANNEL_ID)
.setSmallIcon(...)
.setContentTitle(getContext().getString(R.string.app_name))
...
.setChannelId(CHANNEL_ID)
...
.build()
And don't forget about the NotificationChannel importance and notification priority (set them to high/max if needed)
You updated your channel importance, which is not possible as stated in the documentation (https://developer.android.com/training/notify-user/channels#CreateChannel).
So your problem should be resolved by changing the channelId to something other than "1", as the ids for Channels must be unique.
Here is my kotlin class all you need is to call notificate(title: String, text: String) method, if you want it in java you can convert it
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationManager
import android.content.Context
import android.support.v4.app.NotificationCompat
import beacon.geisoft.org.beacontrakerkotlin_rebuild.R
import android.os.Build
import android.support.annotation.RequiresApi
import android.support.v4.content.ContextCompat.getSystemService
import android.app.NotificationChannel
import android.app.PendingIntent
import android.content.Intent
import android.graphics.Color
import android.media.RingtoneManager
import android.support.v4.content.ContextCompat.getSystemService
import android.support.v4.app.NotificationManagerCompat
import beacon.geisoft.org.beacontrakerkotlin_rebuild.activities.MainActivity
import android.preference.PreferenceManager
import android.content.SharedPreferences
class Notifications (var context: Context){
/**
* Send notification to the client device
* #param text String
*/
#SuppressLint("PrivateResource")
private fun notificate(title: String, text: String, id: Int, notificationManager: NotificationManager) {
val intent1 = Intent(context, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(context, 123, intent1, PendingIntent.FLAG_UPDATE_CURRENT)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && notificationManager.getNotificationChannel("beacon.geisoft.org.beacontraker_rebuild") == null) {
val chan2 = NotificationChannel("beacon.geisoft.org.beacontraker_rebuild", "Pazienti", NotificationManager.IMPORTANCE_HIGH)
chan2.lightColor = Color.BLUE
chan2.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
notificationManager.createNotificationChannel(chan2)
/*
notificationManager.createNotificationChannel(NotificationChannel("beacon.geisoft.org.beacontraker_rebuild",
"Pazienti", NotificationManager.IMPORTANCE_HIGH))*/
}
val builder = NotificationCompat.Builder(context, "beacon.geisoft.org.beacontraker_rebuild")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setContentTitle(title) // required
.setContentText(text) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.beaconicon32) // required
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.beaconicon64))
.setSound(defaultSoundUri)
}else {
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setContentTitle(title)
.setContentText(text)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.beaconicon32) // required
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.beaconicon64))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(defaultSoundUri)
}
notificationManager.notify(id, builder.build());
}
fun notificate(title: String, text: String, id: Int){
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
notificate(title, text, id, notificationManager!!)
}
fun notificate(title: String, text: String){
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
var num: Int
do {
num = (Math.random() * 100).toInt()
} while (notificationExist(notificationManager!!, num))
notificate(title, text, num, notificationManager)
}
fun notificationExist(notificationManager: NotificationManager, id: Int): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val notifications =
notificationManager.activeNotifications
for (notification in notifications) {
if (notification.getId() == id) {
return true
}
}
}
return false
}
}