Skip to content

Instantly share code, notes, and snippets.

@kishan-vadoliya
Created December 20, 2023 05:05
Show Gist options
  • Save kishan-vadoliya/0d91c1c4a2bdbbf9d72bd5198415742a to your computer and use it in GitHub Desktop.
Save kishan-vadoliya/0d91c1c4a2bdbbf9d72bd5198415742a to your computer and use it in GitHub Desktop.
Reminder Module
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <!-- Notification Permission -->
<application ...>
<receiver
android:name=".notifyme.NotificationPublisher"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
<receiver
android:name=".notifyme.BootNotifyMe"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
</application>
</manifest>
// AppDatabaseRoom.kt
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
@Database(
entities = [ReminderTable::class],
version = Constant.ROOM_DB_VERSION,
exportSchema = false,
)
abstract class AppDatabaseRoom : RoomDatabase() {
abstract fun reminderDAO(): ReminderDAO
companion object {
private var INSTANCE: AppDatabaseRoom? = null
fun getInstance(context: Context): AppDatabaseRoom {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(
context.applicationContext, AppDatabaseRoom::class.java, Constant.ROOM_DB_NAME
)
.allowMainThreadQueries()
.build()
}
return INSTANCE as AppDatabaseRoom
}
}
================================================================================================
// ReminderDAO.kt
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
@Dao
interface ReminderDAO {
@Query("SELECT * FROM tbl_reminder ORDER BY custom_id DESC")
fun getAllReminder(): MutableList<ReminderTable>
@Insert
fun addReminder(contentTable: ReminderTable)
@Update
fun updateReminder(contentTable: ReminderTable)
@Delete
fun deleteReminder(contentTable: ReminderTable)
@Query("DELETE FROM tbl_reminder WHERE g_email = :g_email")
fun deleteUserReminder(g_email: String)
@Query("DELETE FROM tbl_reminder WHERE id = :notificationId")
fun deleteReminderById(notificationId: String)
@Query("DELETE FROM tbl_reminder WHERE imagepath = :imageName")
fun deleteReminderByImageName(imageName: String)
@Query("SELECT * FROM tbl_reminder WHERE id = :notificationId")
fun getReminderById(notificationId: String): ReminderTable?
@Query("SELECT * FROM tbl_reminder WHERE custom_id = :notificationId")
fun getReminderByCustomId(notificationId: String): ReminderTable?
@Query("SELECT * FROM tbl_reminder WHERE custom_id = :customerID LIMIT 1")
fun getReminderByCustId(customerID: String): ReminderTable
@Query("SELECT * FROM tbl_reminder WHERE imagepath = :imagePath")
fun getSingleReminderByImagePath(imagePath: String): ReminderTable
@Query("SELECT COUNT(*) FROM tbl_reminder ORDER BY id DESC")
fun getTotalRemindersCount(): Int
@Query("SELECT EXISTS (SELECT 1 FROM tbl_reminder WHERE serverId = :serverId)")
fun getSingleReminderExistByServerId(serverId: Int): Boolean
@Query("SELECT * FROM tbl_reminder WHERE templateName = :templateName")
fun getSingleReminderByTemplateName(templateName: String): ReminderTable?
@Query("SELECT EXISTS (SELECT 1 FROM tbl_reminder WHERE templateName = :templateName)")
fun getSingleReminderExistByTemplateName(templateName: String): Boolean
@Query("SELECT * FROM tbl_reminder WHERE g_email = :g_email OR g_email = ''")
fun getReminderData(g_email: String): List<ReminderTable?>
@Query("DELETE FROM tbl_reminder WHERE templateName = :templateName")
fun deleteReminderByTemplateName(templateName: String)
}
================================================================================================
//DataBaseUtils.kt
import android.app.NotificationManager
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import java.io.File
object DataBaseUtils {
fun getReminders(activity: Context): ArrayList<ReminderItem?> {
val reminderTable = MyApplication.instance.appDatabase.reminderDAO().getReminderData(
(if (DBConstant.isUserSignedIn(activity)) MyApplication.instance.storeUserData.getString(
Constant.LoginUser.EMAIL
) else "")!!
)
val reminderList = ArrayList<ReminderItem?>()
if (!GoogleLoginHelper.isUserSignedIn()) {
reminderList.add(null)
}
reminderTable.forEachIndexed { index, contentTable ->
reminderList.add(
ReminderItem(
contentTable?.id.toString(),
contentTable!!.imagepath,
contentTable.image_width,
contentTable.image_height,
contentTable.time,
contentTable.custom_id,
contentTable.templateName
)
)
}
reminderList.sortWith { o1, o2 ->
if (o1 != null && o2 != null) {
o1.calenderTime!!.compareTo(o2.calenderTime!!)
} else -1
}
return ArrayList(reminderList.asReversed())
}
fun deleteReminder(reminderDAO: ReminderDAO, notificationId: String) {
try {
reminderDAO.deleteReminderById(notificationId)
} catch (e: Exception) {
e.printStackTrace()
}
}
fun updateReminderTime(
reminderDAO: ReminderDAO,
notificationId: String,
time: Long,
serverId: Int = 0
) {
try {
val contentTable = reminderDAO.getReminderById(notificationId)
if (contentTable != null) {
contentTable.time = time
contentTable.serverId = serverId
contentTable.custom_id = System.currentTimeMillis().toString()
contentTable.g_email =
MyApplication.instance.storeUserData.getString(Constant.LoginUser.EMAIL)!!
reminderDAO.updateReminder(contentTable)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
fun updateReminderTimeByCustomId(
reminderDAO: ReminderDAO,
notificationId: String,
time: Long,
serverId: Int = 0
) {
try {
val contentTable = reminderDAO.getReminderByCustId(notificationId)
if (contentTable != null) {
contentTable.time = time
contentTable.serverId = serverId
contentTable.custom_id = System.currentTimeMillis().toString()
contentTable.g_email =
MyApplication.instance.storeUserData.getString(Constant.LoginUser.EMAIL)!!
reminderDAO.updateReminder(contentTable)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
fun getSingleReminderByImagePath(
reminderDAO: ReminderDAO,
imagePath: String
): ArrayList<ReminderItem> {
val reminder = reminderDAO.getSingleReminderByTemplateName(imagePath)
val remindersList = ArrayList<ReminderItem>()
try {
if (reminder != null)
remindersList.add(
ReminderItem(
reminder.id.toString(),
reminder.imagepath,
reminder.image_width,
reminder.image_width,
reminder.time,
reminder.custom_id
)
)
} catch (e: Exception) {
e.printStackTrace()
}
return remindersList
}
fun getSingleReminderById(
reminderDAO: ReminderDAO,
reminderId: String
): ReminderTable? {
return reminderDAO.getReminderById(reminderId)
}
fun getSingleReminderByCustomerId(
reminderDAO: ReminderDAO,
customerID: String
): ReminderItem {
val reminder = reminderDAO.getReminderByCustId(customerID)
return ReminderItem(
reminder.id.toString(),
reminder.imagepath,
reminder.image_width,
reminder.image_width,
reminder.time,
reminder.custom_id
)
}
fun getTotalRemindersCount(reminderDAO: ReminderDAO): Int {
return reminderDAO.getTotalRemindersCount()
}
fun selectAndDeleteReminderByImagePath(
reminderDAO: ReminderDAO,
activity: AppCompatActivity,
imageName: String
) {
try {
val reminderData = reminderDAO.getSingleReminderByImagePath(imageName)
reminderDAO.deleteReminderById(reminderData.id.toString())
val mNotificationManager =
activity.getSystemService(AppCompatActivity.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager.cancel(reminderData.id)
reminderDAO.deleteReminderByImageName(reminderData.id.toString())
} catch (e: Exception) {
e.printStackTrace()
}
}
}
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.media.RingtoneManager
import android.os.Build
import androidx.core.app.NotificationCompat
class NotificationPublisher : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val notificationId = intent.getStringExtra(NOTIFICATION_ID)
val reminder = DataBaseUtils.getSingleReminderById(
MyApplication.instance.reminderDAO,
notificationId.toString()
)
var title = ""
var content = ""
var imagePath = ""
var rrule = ""
var dstart = ""
var led_color = -1
var image_width = 0
var image_height = 0
var small_icon = -1
var large_icon = -1
if (reminder != null) {
title = if (reminder.title == null) "" else reminder.title
content = reminder.content
imagePath = reminder.imagepath
rrule = reminder.rrule.toString()
dstart = reminder.dstart.toString()
led_color = reminder.led_color
image_width = reminder.image_width
image_height = reminder.image_height
small_icon = if (reminder.small_icon != null) reminder.small_icon.toInt() else -1
large_icon = if (reminder.large_icon != null) reminder.large_icon.toInt() else -1
}
if (title.isNotEmpty()) {
val mBuilder = NotificationCompat.Builder(context, notificationId!!)
if (small_icon != -1) {
mBuilder.setSmallIcon(small_icon)
} else {
mBuilder.setSmallIcon(R.drawable.ic_noti_small)
}
if (large_icon != -1) {
val largeIcon = BitmapFactory.decodeResource(context.resources, large_icon)
mBuilder.setLargeIcon(largeIcon)
}
mBuilder.setContentTitle(title)
mBuilder.setContentText(content)
mBuilder.color = Color.WHITE
mBuilder.setVibrate(longArrayOf(1000, 1000, 1000))
mBuilder.setAutoCancel(true)
val intent1 = Intent(context, SplashActivity::class.java)
intent1.putExtra(Constant.KEY_ID, notificationId)
intent1.putExtra(Constant.KEY_IMAGE, imagePath)
intent1.putExtra(Constant.KEY_TEMPLATE_WIDTH, image_width)
intent1.putExtra(Constant.KEY_TEMPLATE_HEIGHT, image_height)
intent1.flags = (Intent.FLAG_ACTIVITY_CLEAR_TOP
or Intent.FLAG_ACTIVITY_SINGLE_TOP)
val pIntent = PendingIntent.getActivity(
context, notificationId.toInt(), intent1,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
mBuilder.setContentIntent(pIntent)
val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
mBuilder.setSound(uri)
val notification = mBuilder.build()
notification.ledARGB = led_color
notification.flags = Notification.FLAG_SHOW_LIGHTS
notification.ledOnMS = 300
notification.ledOffMS = 1000
val mNotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val nc = NotificationChannel(
notificationId,
notificationId,
NotificationManager.IMPORTANCE_HIGH
)
nc.enableLights(true)
nc.lightColor = led_color
mNotificationManager.createNotificationChannel(nc)
// mNotificationManager.notify(notificationId.toInt(), notification)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if(MyApplication.instance.storeUserData.getBoolean(Constant.IS_NOTIFICATION_ENABLED))
mNotificationManager.notify(notificationId.toInt(), notification)
} else mNotificationManager.notify(notificationId.toInt(), notification)
}
}
companion object {
var NOTIFICATION_ID = "notification_id"
}
}
import android.app.AlarmManager
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import androidx.annotation.StringRes
import androidx.annotation.UiThread
import java.util.Calendar
import java.util.Date
open class NotifyMe protected constructor(val builder: Builder) {
class Builder(var context: Context) {
var title: CharSequence? = null
var content: CharSequence? = null
var key: CharSequence? = null
var rrule: CharSequence? = null
var imagePath: CharSequence? = null
protected var id: Long? = null
var delay = 0
var time = Date()
var dstart: Date? = Date()
var actions = arrayOfNulls<String>(0)
var actions_text = arrayOfNulls<String>(0)
var actions_dismiss = arrayOfNulls<String>(0)
var actions_collapse = arrayOfNulls<String>(0)
var color = -1
var led_color = 0
var image_width = 0
var templateName = ""
var serverId = 0
var image_height = 0
var small_icon = -1
var large_icon = -1
fun delay(delay: Int): Builder {
this.delay = delay
return this
}
// fun rrule(str: String?): Builder {
// try {
// val r = RecurrenceRule(str)
// rrule = str
// } catch (e: Exception) {
// }
// return this
// }
fun dstart(dstart: Date?): Builder {
this.dstart = time
return this
}
fun dstart(dstart: Calendar): Builder {
this.dstart = dstart.time
return this
}
fun small_icon(small_icon: Int): Builder {
this.small_icon = small_icon
return this
}
fun large_icon(large_icon: Int): Builder {
this.large_icon = large_icon
return this
}
fun led_color(red: Int, green: Int, blue: Int, alpha: Int): Builder {
val color =
alpha and 0xff shl 24 or (red and 0xff shl 16) or (green and 0xff shl 8) or (blue and 0xff)
led_color = color
return this
}
fun image_width(image_width: Int): Builder {
this.image_width = image_width
return this
}
fun image_height(image_height: Int): Builder {
this.image_height = image_height
return this
}
fun color(red: Int, green: Int, blue: Int, alpha: Int): Builder {
val color =
alpha and 0xff shl 24 or (red and 0xff shl 16) or (green and 0xff shl 8) or (blue and 0xff)
this.color = color
return this
}
fun serverId(serverId: Int): Builder {
this.serverId = serverId
return this
}
fun templateName(templateName: String): Builder {
this.templateName = templateName
return this
}
@JvmOverloads
fun addAction(
intent: Intent,
text: String?,
dismiss: Boolean = true,
collapse: Boolean = true
): Builder {
val temp = arrayOfNulls<String>(actions.size + 1)
for (i in actions.indices) {
temp[i] = actions[i]
}
val temp_collapse = arrayOfNulls<String>(actions_collapse.size + 1)
for (i in actions_collapse.indices) {
temp_collapse[i] = actions_collapse[i]
}
val temp_text = arrayOfNulls<String>(actions_text.size + 1)
for (i in actions_text.indices) {
temp_text[i] = actions_text[i]
}
val temp_dismiss = arrayOfNulls<String>(actions_dismiss.size + 1)
for (i in actions_dismiss.indices) {
temp_dismiss[i] = actions_dismiss[i]
}
temp_dismiss[actions_dismiss.size] = dismiss.toString()
temp_collapse[actions_collapse.size] = collapse.toString()
temp_text[actions_text.size] = text
temp[actions.size] = intent.toUri(0)
actions_text = temp_text
actions = temp
actions_dismiss = temp_dismiss
actions_collapse = temp_collapse
return this
}
fun time(time: Date): Builder {
this.time = time
return this
}
fun time(time: Calendar): Builder {
this.time = time.time
return this
}
fun title(title: CharSequence?): Builder {
this.title = title
return this
}
fun title(@StringRes title: Int): Builder {
title(context.getText(title))
return this
}
fun title(title: String?): Builder {
this.title = title
return this
}
fun key(key: CharSequence?): Builder {
this.key = key
return this
}
fun key(@StringRes key: Int): Builder {
key(context.getText(key))
return this
}
fun key(key: String?): Builder {
this.key = key
return this
}
fun content(content: CharSequence?): Builder {
this.content = content
return this
}
fun content(@StringRes content: Int): Builder {
title(context.getText(content))
return this
}
fun content(content: String?): Builder {
this.content = content
return this
}
fun imagePath(imagePath: String?): Builder {
this.imagePath = imagePath
return this
}
@UiThread
fun build(): NotifyMe {
return NotifyMe(this)
}
}
companion object {
private const val strSeparator = "__,__"
fun convertArrayToString(array: Array<String?>): String {
var str = ""
for (i in array.indices) {
str = str + array[i]
// Do not append comma at the end of last element
if (i < array.size - 1) {
str = str + strSeparator
}
}
return str
}
@JvmStatic
fun convertStringToArray(str: String): Array<String> {
return str.split(strSeparator).toTypedArray()
}
fun cancel(context: Context, notificationId: Int) {
try {
val mNotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
DataBaseUtils.deleteReminder(
MyApplication.instance.reminderDAO,
notificationId.toString()
)
mNotificationManager.cancel(notificationId)
} catch (e: Exception) {
e.printStackTrace()
}
}
fun cancel(context: Context, key: String) {
try {
val mNotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val reminder = DataBaseUtils.getSingleReminderByCustomerId(
MyApplication.instance.reminderDAO,
key
)
val notificationId = reminder.notificationAutoId
DataBaseUtils.deleteReminder(
MyApplication.instance.reminderDAO,
reminder.notificationAutoId
)
/* val mDbHelper = DbHelper(context)
val db: SQLiteDatabase = mDbHelper.writableDatabase
val cursor = db.rawQuery(
"SELECT * FROM " + ReminderStructure.TABLE_NAME.toString() + " WHERE custom_id = ? LIMIT 1",
arrayOf(key)
)
if (cursor.count > 0) {
cursor.moveToFirst()
val notificationId =
cursor.getInt(cursor.getColumnIndex(ReminderStructure.ReminderInfo.NOTIFICATION_AUTO_ID))
db.delete(
ReminderStructure.TABLE_NAME,
"${ReminderStructure.ReminderInfo.NOTIFICATION_AUTO_ID} = $notificationId",
null
)
db.close()
cursor.close()
mNotificationManager.cancel(notificationId)
}*/
mNotificationManager.cancel(notificationId.toInt())
} catch (e: Exception) {
e.printStackTrace()
}
}
@JvmStatic
fun init(context: Context) {
val reminderList = DataBaseUtils.getReminders(context)
if (reminderList.size > 0) {
reminderList.forEach {
if (it != null) {
val time = it.calenderTime
val id = it.notificationAutoId
if (time!! > System.currentTimeMillis()) {
scheduleNotification(context, id!!, time)
}
}
}
}
}
@JvmStatic
fun scheduleNotification(context: Context, notificationId: String, time: Long) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, NotificationPublisher::class.java)
intent.putExtra(NotificationPublisher.NOTIFICATION_ID, notificationId)
intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
val pendingIntent = PendingIntent.getBroadcast(
context,
notificationId.toInt(),
intent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
alarmManager[AlarmManager.RTC_WAKEUP, time] = pendingIntent
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent)
}
@JvmStatic
fun deleteNotificationFromAlarm(context: Context, notificationId: String) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, NotificationPublisher::class.java)
val pendingIntent = PendingIntent.getBroadcast(
context,
notificationId.toInt(),
intent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
alarmManager.cancel(pendingIntent)
}
}
init {
val cal = Calendar.getInstance()
cal.time = builder.time
cal.add(Calendar.MILLISECOND, builder.delay)
val dsStart = if (builder.dstart == null) {
cal.timeInMillis
} else {
val dstart_cal = Calendar.getInstance()
dstart_cal.time = builder.dstart!!
dstart_cal.timeInMillis
}
val reminderTable = ReminderTable(
title = builder.title.toString(),
time = cal.timeInMillis,
dstart = dsStart,
actions = convertArrayToString(builder.actions),
actions_text = convertArrayToString(builder.actions_text),
actions_dismiss = convertArrayToString(builder.actions_dismiss),
actions_collapse = convertArrayToString(builder.actions_collapse),
custom_id = builder.key.toString(),
led_color = builder.led_color,
image_width = builder.image_width,
image_height = builder.image_height,
color = builder.color,
small_icon = builder.small_icon.toString(),
large_icon = builder.large_icon.toString(),
imagepath = builder.imagePath.toString(),
content = builder.content.toString(),
templateName = builder.templateName,
g_email = MyApplication.instance.storeUserData.getString(Constant.LoginUser.EMAIL)!!,
serverId = builder.serverId
)
MyApplication.instance.reminderDAO.addReminder(reminderTable)
val id = DataBaseUtils.getSingleReminderByImagePath(
MyApplication.instance.reminderDAO,
builder.templateName
)[0].notificationAutoId
val currentCalendar = Calendar.getInstance()
if (cal.after(currentCalendar)) {
scheduleNotification(builder.context, id, cal.timeInMillis)
}
}
}
// Notification Permision Runtime
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (checkSelfPermission(
activity!!,
Manifest.permission.POST_NOTIFICATIONS
) == PackageManager.PERMISSION_GRANTED
) {
MyApplication.instance.storeUserData.setBoolean(
Constant.IS_NOTIFICATION_ENABLED,
true
)
addReminder(index)
} else {
requestPermissionLauncherNoti.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
class ReminderFragment : BaseFragment(), DatePickerDialog.OnDateSetListener,
TimePickerDialog.OnTimeSetListener {
private var day: Int = -1
private var month: Int = -1
private var year: Int = -1
private var hour: Int = -1
private var minute: Int = -1
private var myDay: Int = -1
private var myMonth: Int = -1
private var myYear: Int = -1
private var myHour: Int = -1
private var myMinute: Int = -1
private lateinit var now: Calendar
// get all reminder
appDatabase?.reminderDAO()?.getAllReminder()
// Add Reminder
private fun addReminder(index: Int) {
tempPosition = index
now = Calendar.getInstance()
year = now[Calendar.YEAR]
month = now[Calendar.MONTH]
day = now[Calendar.DAY_OF_MONTH]
val datePickerDialog =
DatePickerDialog(
activity!!,
android.R.style.Theme_Material_Dialog_Alert,
this,
year,
month,
day
)
datePickerDialog.datePicker.minDate = System.currentTimeMillis()
datePickerDialog.setCancelable(false)
datePickerDialog.show()
}
override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
myYear = year
myDay = day
myMonth = (month + 1)
now[Calendar.YEAR] = year
now[Calendar.MONTH] = month
now[Calendar.DAY_OF_MONTH] = dayOfMonth
hour = now[Calendar.HOUR_OF_DAY]
minute = now[Calendar.MINUTE]
val timePickerDialog = TimePickerDialog(
activity!!,
android.R.style.Theme_Material_Dialog_Alert, this,
hour,
minute,
false
)
timePickerDialog.setCancelable(false)
timePickerDialog.show()
}
override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
myHour = hourOfDay
myMinute = minute
now[Calendar.HOUR_OF_DAY] = hourOfDay
now[Calendar.MINUTE] = minute
if (now.timeInMillis > System.currentTimeMillis()) {
if (isReminderAlreadyAdded) {
Utils.showSnackBar(
binding.clSavedParent,
getString(R.string.reminder_edited_you_ll_be_notified_on_time)
)
NotifyMe.deleteNotificationFromAlarm(
activity!!,
reminderImageNameList[0].notificationAutoId
)
// MyApplication.instance.dbHelper.updateReminderTime(
DataBaseUtils.updateReminderTimeByCustomId(
MyApplication.instance.reminderDAO,
reminderImageNameList[0].customId,
now.timeInMillis
)
NotifyMe.scheduleNotification(
activity!!,
reminderImageNameList[0].notificationAutoId,
now.timeInMillis
)
} else {
NotifyMe.Builder(activity!!)
.title(getString(R.string.notification_title))
.content(getString(R.string.notification_desc))
.color(255, 0, 0, 255)
.led_color(255, 255, 255, 255)
.imagePath(files[tempPosition!!]!!.file.absolutePath)
.time(now)
.image_width(files[tempPosition!!]!!.width)
.image_height(files[tempPosition!!]!!.height)
.key(System.currentTimeMillis().toString())
.large_icon(R.mipmap.ic_launcher_round)
.templateName(files[tempPosition!!]!!.template_name)
.build()
Utils.showSnackBar(
binding.clSavedParent,
getString(R.string.reminder_added)
)
}
loginViewModel.addUserReminder(
reminderDate = SimpleDateFormat(Constant.REMINDER_DATE_FORMAT).format(Date(now.timeInMillis)),
reminderTime = SimpleDateFormat(Constant.REMINDER_TIME_FORMAT).format(Date(now.timeInMillis)),
serverId = files[tempPosition!!]!!.server_id.toInt()
)
val intent4 = Intent()
intent4.action = Constant.ACTION_UPDATE_REMINDER
activity!!.sendBroadcast(intent4)
} else {
Utils.showSnackBar(
binding.clSavedParent,
MyApplication.instance.getString(R.string.you_can_not_pick)
)
}
}
// Update Reminder
private fun updateReminder() {
tempPosition = TEMPLATE_ID
now = Calendar.getInstance()
year = now[Calendar.YEAR]
month = now[Calendar.MONTH]
day = now[Calendar.DAY_OF_MONTH]
val datePickerDialog =
DatePickerDialog(
requireActivity(), android.R.style.Theme_Material_Dialog_Alert,
this,
year,
month,
day
)
datePickerDialog.datePicker.minDate = System.currentTimeMillis()
datePickerDialog.setCancelable(false)
datePickerDialog.show()
}
override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
myYear = year
myDay = day
myMonth = (month + 1)
now[Calendar.YEAR] = year
now[Calendar.MONTH] = month
now[Calendar.DAY_OF_MONTH] = dayOfMonth
hour = now[Calendar.HOUR_OF_DAY]
minute = now[Calendar.MINUTE]
val timePickerDialog = TimePickerDialog(
requireActivity(),
android.R.style.Theme_Material_Dialog_Alert, this,
hour,
minute,
false
)
timePickerDialog.setCancelable(false)
timePickerDialog.show()
}
@SuppressLint("SimpleDateFormat")
override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
myHour = hourOfDay
myMinute = minute
now[Calendar.HOUR_OF_DAY] = hourOfDay
now[Calendar.MINUTE] = minute
if (now.timeInMillis > System.currentTimeMillis()) {
Utils.showSnackBar(
mBinding.clFragmentReminderParent,
MyApplication.instance.getString(R.string.reminder_edited_you_ll_be_notified_on_time)
)
NotifyMe.deleteNotificationFromAlarm(
requireActivity(),
stringsList[tempPosition!!]!!.notificationAutoId
)
DataBaseUtils.updateReminderTimeByCustomId(
MyApplication.instance.reminderDAO,
stringsList[tempPosition!!]!!.customId,
now.timeInMillis
)
NotifyMe.scheduleNotification(
activity!!,
stringsList[tempPosition!!]!!.notificationAutoId,
now.timeInMillis
)
requireActivity().sendBroadcast(Intent().apply {
action = Constant.ACTION_UPDATE_REMINDER
})
var reminderItem = appDatabase?.myPostDAO()?.getDataByTemplatename(stringsList[tempPosition!!]!!.templateName)
if (reminderItem == null) {
reminderItem = appDatabase?.myPostDAO()?.getDataFromThumbPath(stringsList[tempPosition!!]!!.imagePath)
}
loginViewModel.addUserReminder(
reminderDate = SimpleDateFormat(Constant.REMINDER_DATE_FORMAT).format(Date(now.timeInMillis)),
reminderTime = SimpleDateFormat(Constant.REMINDER_TIME_FORMAT).format(Date(now.timeInMillis)),
serverId = reminderItem?.server_id!!.toInt()
)
reminderAdapter?.notifyItemChanged(tempPosition!!)
} else {
Utils.showSnackBar(
mBinding.clFragmentReminderParent,
MyApplication.instance.getString(R.string.you_can_not_pick)
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment