I'm testing for sending notification using alarm manager when the app is closed. Right now after clicking a button a notification is triggered after 10 seconds and I close the app.
The notification is showing when the app is open but not when closed.
Here is my code:
Triggering notification in TimeTableScheduleActivity:
private fun setUpAlarm(c: Calendar){
val cal = Calendar.getInstance()
cal.add(Calendar.SECOND, 10)
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, AlertReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)
Toast.makeText(this, "notification in 10 secs", Toast.LENGTH_SHORT).show()
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.timeInMillis, pendingIntent)
}
AlertReceiver class:
class AlertReceiver : BroadcastReceiver(){
override fun onReceive(context: Context?, intent: Intent?) {
val intent = Intent(context, TimeTableScheduleActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
val pendingIntent = PendingIntent.getActivity(context, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val builder = NotificationCompat.Builder(context!!, Navigation.CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_stat_call_white)
.setLargeIcon(BitmapFactory.decodeResource(context!!.getResources(), R.mipmap.icon_round))
.setContentTitle("title")
.setContentText("body")
.setColor(Color.parseColor("#138FF7"))
.setContentIntent(pendingIntent)
.setVibrate(longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400))
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setLights(Color.WHITE, 500, 500)
.setPriority(NotificationCompat.PRIORITY_HIGH)
val notificationManagerCompat = NotificationManagerCompat.from(context)
notificationManagerCompat.notify(1, builder.build())
Toast.makeText(context,"alert receive",Toast.LENGTH_LONG).show()
}
}
Related
Hi I am implementing a alarm system in my app. I have an alarm manager that triggers a notification everyday in a certain time. It doesn't work as it intended the notification is not displayed at all. Please can anyone help me with these thank you.
my Alarm set code:
val calender = Calendar.getInstance()
calender[Calendar.HOUR_OF_DAY] = hour
calender[Calendar.MINUTE] = minute
calender[Calendar.SECOND] = 0
calender[Calendar.MILLISECOND] = 0
val pendingIntent = PendingIntent.getBroadcast(
requireContext(),
0,
intent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
alarmManager.setInexactRepeating (
AlarmManager.RTC_WAKEUP,
calender.timeInMillis,
AlarmManager.INTERVAL_DAY,
pendingIntent
)
Broadcast receiver:
class AlarmReceiver : BroadcastReceiver() {
#RequiresApi(Build.VERSION_CODES.O)
override fun onReceive(context: Context?, p1: Intent?) {
val notificationManager =
context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationCompatBuilder =
NotificationCompat.Builder(context, Constants.NOTIFICATION_CHANNEL_ID)
notificationCompatBuilder
.setContentTitle("Prescript")
.setContentText("Medicine time.")
.setSmallIcon(R.mipmap.ic_launcher).priority = NotificationCompat.PRIORITY_DEFAULT
notificationManager.notify(666, notificationCompatBuilder.build())
Log.d("TAG", "onReceive: $notificationCompatBuilder")
// Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
}
}
I'm trying to send notifications using AlarmManager and they are being sent very late. Sometimes they do get sent around the time they're supposed to be sent, but other times they're being sent 2 hours or even 6 hours later than the original time that was set.
This is the BroadcastReceiver() for the notification:
#RequiresApi(Build.VERSION_CODES.O)
class NotificationAlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val i = Intent(context, SplashActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent = PendingIntent.getActivity(
context,
0,
i,
PendingIntent.FLAG_IMMUTABLE
)
val builder = NotificationCompat.Builder(context, Constants.NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification_icon)
.setColor(ContextCompat.getColor(context, R.color.colorPrimary))
.setContentTitle(context.getString(R.string.notification))
.setContentText(NOTIFICATION_CONTEXT_TEXT)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setStyle(NotificationCompat.BigTextStyle().bigText(NOTIFICATION_CONTEXT_TEXT))
.setContentIntent(pendingIntent)
.setAutoCancel(true)
with(NotificationManagerCompat.from(context)) {
notify(Constants.NOTIFICATION_NOTIFICATION_ID, builder.build())
}
}
companion object {
private val NOTIFICATION_CONTEXT_TEXT: String by lazy { "Lorem ipsum" }
}
}
And this is the code for sending the notification:
notificationCalendar = Calendar.getInstance()
notificationCalendar[Calendar.HOUR_OF_DAY] = 8
notificationCalendar[Calendar.MINUTE] = 0
notificationCalendar[Calendar.SECOND] = 0
notificationCalendar[Calendar.MILLISECOND] = 0
if ((Calendar.getInstance().timeInMillis - notificationCalendar.timeInMillis) > 0) {
notificationCalendar.add(Calendar.DAY_OF_MONTH, 1)
}
notificationAlarmMgr = context.getSystemService(Context.ALARM_SERVICE) as? AlarmManager
notificationAlarmIntent = Intent(
context,
NotificationAlarmReceiver::class.java
).let { intent ->
PendingIntent.getBroadcast(
context,
NOTIFICATION_ID,
intent,
PendingIntent.FLAG_IMMUTABLE
)
}
notificationAlarmMgr?.setInexactRepeating(
AlarmManager.RTC_WAKEUP,
notificationCalendar.timeInMillis,
AlarmManager.INTERVAL_DAY,
notificationAlarmIntent
)
Why are my notifications being sent so late? What can I do to ensure they get sent at least within a minute of the desired time?
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.
so I'm new to coding and I'm making an app for Muslims prayer times and I want an alarms to be set repeatedly on these times
I tried to many things but It doesn't works!
I have a praytimes class and if anyone wants it I'll put it
I will be more thankful, if you could help me on how to set an alarm for 1 prayer so I could do the rest.
Main Activity
val latitude = 30.354802
val longitude = 42.2461069
val timezonoffset = 3.0
val timeZoneId = "Middle East/Alowiqila"
val prayTimes = PrayTimes()
prayTimes.timeFormat = prayTimes.time12//
prayTimes.calcMethod = prayTimes.makkah// Muslim World League (MWL)
prayTimes.asrJuristic = prayTimes.hanafi// Shafii (standard)
prayTimes.adjustHighLats = prayTimes.angleBased
val offsets = intArrayOf(0, 0, 0, 0, 0, 0, 0) // {Fajr,Sunrise,Dhuhr,Asr,Sunset,Maghrib,Isha}
prayTimes.tune(offsets)
val cal = Calendar.getInstance(TimeZone.getTimeZone(timeZoneId))
cal.time = Date()
val times = prayTimes.getPrayerTimes(cal, latitude, longitude, timezonoffset)
println("prayer times for Alowiqila")
System.out.println("Fajr : " + times.get(0))
System.out.println("Sunrise : " + times.get(1))
System.out.println("Duhr : " + times.get(2))
System.out.println("Asr : " + times.get(3))
System.out.println("Sunset : " + times.get(4))
System.out.println("Magrib : " + times.get(5))
System.out.println("Isha : " + times.get(6))
// I want the Alarm to be set to the code above it
fun startAlarm(isNotification:Boolean, isRepeat:Boolean) {
val manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val myIntent= Intent(this#MainActivity, AlarmReceiver::class.java)
val pendingIntent:PendingIntent
// SET TIME HERE
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, 15)
calendar.set(Calendar.MINUTE, 20)
pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0)
if (!isRepeat)
manager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + 3000, pendingIntent)
else
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_DAY, pendingIntent)
}
AlarmReceiver.kt
and here is my alarm receiver in witch I've added me notifications
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val builder = NotificationCompat.Builder(context)
val myIntent = Intent(context, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
context,
0,
myIntent,
FLAG_ONE_SHOT
)
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setContentTitle("موعد الاذان")
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_LIGHTS or Notification.DEFAULT_SOUND)
.setContentInfo("Info")
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, builder.build())
}
You have to put different requestCode in pending intent, each alarm manager requires different requestCode.
in your mainActivity
pendingIntent = PendingIntent.getBroadcast(this, (0..2147483647).random(), myIntent, 0)
I try to push notification by date to my app. I allready build the broadcast reciever and for some reason it didn't push the notification.
This is my code:
saveTime?.setOnClickListener() //save time notification
{
val hour: Int = tp!!.hour
val min: Int = tp!!.minute
var text = "" + hour + ":" + min
var calendar: Calendar = Calendar.getInstance()
calendar.set(Calendar.DAY_OF_WEEK,1)
calendar.set(Calendar.DAY_OF_WEEK,Calendar.FRIDAY)
calendar.set(Calendar.HOUR_OF_DAY,hour)
calendar.set(Calendar.MINUTE,min)
calendar.set(Calendar.SECOND, 0);
val intent = Intent()
val pendingIntent = PendingIntent.getActivity(this.activity,0,intent,PendingIntent.FLAG_UPDATE_CURRENT)
var alarmManager = this.activity.getSystemService(ALARM_SERVICE) as AlarmManager
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.timeInMillis, AlarmManager.INTERVAL_DAY,pendingIntent)
}
And here you'll see my broadcast reciever class:
class MyReciver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val timeAlert = System.currentTimeMillis()
val notificationManager = context
.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationIntent = Intent(context, MainActivity::class.java)
notificationIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
val pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT)
//val alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notification = Notification.Builder(context)
.setContentTitle("some title:")
.setContentText("some text")
.setSmallIcon(R.drawable.notification_icon_background)
.setAutoCancel(true).setWhen(timeAlert)
.setContentIntent(pendingIntent)
notificationManager.notify(0, notification.build())
}
}