How to set multiple alarms in kotlin? - android

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)

Related

Notification doesn't show when alarm is triggered

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

How to schedule recurring notifications in kotlin?

I've been looking for this for a couple of hours but I haven't found anything helpful. Right now, I have an activity (called other_recurringreminder) that sets a time (fomartted calendar, HH:mm; string), repetition frequency (int), repetition unit (like minutes, hours, days; string), whether it's on or off (bool), and a name (string)
In other_recurringreminder.kt, I have this function:
fun sendnotification()
{
val channelID = "channel1"
val notificationID = 1
val sharedPreferences: SharedPreferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE)
val builder = NotificationCompat.Builder(this, "channelID")
.setSmallIcon(R.drawable.centr)
.setColor(resources.getColor(R.color.purple))
.setContentTitle(sharedPreferences.getString("Alarm1Name_USERPREFS", "Reminder 1"))
.setContentText(getString(R.string.notif_recurringreminders))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
with(NotificationManagerCompat.from(this)) {
notify(notificationID, builder.build())
}
}
Which sends the notification when called.
How can I make it so that my app sends this notification at a time from SharedPreferences, with a title from SP, and repeats every x units from SP?
Should this function be in another kotlin file?
Can this work even after a restart, when my app hasn't yet been opened?If I want to schedule more than one notif with different values, do I need to duplicate anything?
Sorry if it's a dumb question, I'm fairly new to kotlin. and thanks!
you can use alarm manager for it.
first create a class with broadcast receiver like
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
Log.d("this", "notify")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val intent = Intent(context, AlarmActivity2::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
val builder = NotificationCompat.Builder(context, "111")
.setSmallIcon(R.drawable.blue_stringart)
.setContentTitle("Alarm is running")
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setDefaults(NotificationCompat.DEFAULT_SOUND)
.setDefaults(NotificationCompat.DEFAULT_VIBRATE)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.addAction(R.drawable.ic_baseline_stop_24,"Stop",pendingIntent)
.setContentIntent(pendingIntent)
val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
val r = RingtoneManager.getRingtone(context, notification)
r.play()
val notificationManagerCompat = NotificationManagerCompat.from(context)
notificationManagerCompat.notify(123, builder.build())
}
}
}
after that go to your activity class make 2 method and call in oncreate
private fun setAlarm1() {
var calender: Calendar
calender = Calendar.getInstance()
calender.set(Calendar.HOUR_OF_DAY, PUT_YOUR_ALARM HOUR)
calender.set(Calendar.MINUTE, PUT_YOUR_ALARM MINUTE)
calender.set(Calendar.SECOND, 0)
alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val thuReq: Long = Calendar.getInstance().timeInMillis + 1
var reqReqCode = thuReq.toInt()
if (calender.timeInMillis < System.currentTimeMillis()) {
calender.add(Calendar.DAY_OF_YEAR, 1)
}
val alarmTimeMilsec = calender.timeInMillis
val intent = Intent(this, AlarmReceiver::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
val pendingIntent = PendingIntent.getBroadcast(this, reqReqCode, intent, 0)
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calender.timeInMillis,
HERE_PUT_YOUR_HOUR * 60 * 60 * 1000,
pendingIntent
)
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Alarmclock Channel"
val description = " Reminder Alarm manager"
val importance = NotificationManager.IMPORTANCE_HIGH
val notificationChannel = NotificationChannel(CHANNELID, name, importance)
notificationChannel.description = description
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(notificationChannel)
}
}
Note - Must to do(go to your app setting and give notification permission on) 1.alarmManager.setRepeating here you can use your alarm type as your wish. 2.requestcode must be unique for each alarm. 3. you must take a alarm time and keep in calender.timeInMillis which is you expecting alarm time.
still problem comments below

How to make notification every 7 p.m?

Hello guys i'm making app for tracking insulin injections for my mom. I want to make app that will create notification automatically every 7 p.m. Can you advice me how to do it? I tried to google it but i'm only found videos with notifications by clicking button but it will not work for me because i want my app to create notifications even when app is closed so i need something like Services that will always by alive even app is closed
You firstly need to instantiate a Broadcast Receiver class and override their onReceive function.
Don't forget to add this to your manifest.
<receiver android:name=".AlertReceiver" />
Override the function as talked.
class AlertReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Glide.with(context).asBitmap().load(R.drawable.ic_diagnosis_24dp).into(object : CustomTarget<Bitmap>() {
override fun onLoadCleared(placeholder: Drawable?) {}
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
val notificationHelper = NotificationHelper(context,resource,intent.extras!!.getInt("requestCode"))
val nb = notificationHelper.channelNotification
notificationHelper.manager?.notify(1, nb.build())
}
})
}
}
You can prepare a Notification Helper just in case you want to deal with things in a better format.
class NotificationHelper(base: Context?, healthReportIcon: Bitmap, requestCode: Int) : ContextWrapper(base) {
private val healthIcon = healthReportIcon
private var mManager: NotificationManager? = null
private lateinit var beforeTime: String
private var intentActivity: Class<*>
#TargetApi(Build.VERSION_CODES.O)
private fun createChannel() {
val channel = NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH)
manager!!.createNotificationChannel(channel)
}
val manager: NotificationManager? get() {
if (mManager == null) {
mManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
}
return mManager
}
val channelNotification: NotificationCompat.Builder get() = NotificationCompat.Builder(applicationContext, channelID)
.setContentTitle("Reminder!")
.setContentText("Update medical records before $beforeTime")
.setSmallIcon(R.drawable.ic_round_local_hospital_24)
.setColor(ContextCompat.getColor(this,R.color.blue_diff))
.setLargeIcon(healthIcon)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setPriority(NotificationCompat.PRIORITY_MAX)
.setTimeoutAfter(1800000)
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(baseContext, 0, Intent(baseContext, intentActivity), 0))
companion object {
const val channelID = "phoneId"
const val channelName = "phoneChannel"
}
init {
when (requestCode) {
0 -> {
beforeTime = "12:30 AM"
}
1 -> {
beforeTime = "6:30 AM"
}
2 -> {
beforeTime = "12:30 PM"
}
3 -> {
beforeTime = "6:30 PM"
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel()
}
intentActivity = if(FirebaseAuth.getInstance().currentUser!=null) {
HomeActivity::class.java
} else{
Splash::class.java
}
}
}
Finally, set or cancel your alarms in your codebase.
private fun startAlarms() {
val cal0 = Calendar.getInstance()
cal0[Calendar.HOUR_OF_DAY]=24
cal0[Calendar.MINUTE]=0
cal0[Calendar.SECOND]=0
val cal1 = Calendar.getInstance()
cal1[Calendar.HOUR_OF_DAY]=6
cal1[Calendar.MINUTE]=0
cal1[Calendar.SECOND]=0
val cal2 = Calendar.getInstance()
cal2[Calendar.HOUR_OF_DAY]=12
cal2[Calendar.MINUTE]=0
cal2[Calendar.SECOND]=0
val cal3 = Calendar.getInstance()
cal3[Calendar.HOUR_OF_DAY]=18
cal3[Calendar.MINUTE]=0
cal3[Calendar.SECOND]=0
if (cal0.before(Calendar.getInstance())) {
cal0.add(Calendar.DATE, 1)
}
if (cal1.before(Calendar.getInstance())) {
cal1.add(Calendar.DATE, 1)
}
if (cal2.before(Calendar.getInstance())) {
cal2.add(Calendar.DATE, 1)
}
if (cal3.before(Calendar.getInstance())) {
cal3.add(Calendar.DATE, 1)
}
val alarmManager: AlarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, AlertReceiver::class.java)
intent.putExtra("requestCode",0)
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal0.timeInMillis, PendingIntent.getBroadcast(this, 0,intent , PendingIntent.FLAG_UPDATE_CURRENT))
intent.putExtra("requestCode",1)
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal1.timeInMillis, PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT))
intent.putExtra("requestCode",2)
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal2.timeInMillis, PendingIntent.getBroadcast(this, 2,intent, PendingIntent.FLAG_UPDATE_CURRENT))
intent.putExtra("requestCode",3)
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal3.timeInMillis, PendingIntent.getBroadcast(this, 3, intent, PendingIntent.FLAG_UPDATE_CURRENT))
}
private fun cancelAlarms() {
val alarmManager: AlarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, AlertReceiver::class.java)
alarmManager.cancel(PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT))
alarmManager.cancel(PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_CANCEL_CURRENT))
alarmManager.cancel(PendingIntent.getBroadcast(this, 2, intent, PendingIntent.FLAG_CANCEL_CURRENT))
alarmManager.cancel(PendingIntent.getBroadcast(this, 3, intent, PendingIntent.FLAG_CANCEL_CURRENT))
PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT).cancel()
PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_CANCEL_CURRENT).cancel()
PendingIntent.getBroadcast(this, 2, intent, PendingIntent.FLAG_CANCEL_CURRENT).cancel()
PendingIntent.getBroadcast(this, 3, intent, PendingIntent.FLAG_CANCEL_CURRENT).cancel()
}
Hope this helped you out. Happy Coding! :)

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

cant push notification by date in kotlin

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

Categories

Resources