I have a situation where the app has to locally generate a notification to the user. If the app is not opened for the last 24 hours and the internet is off.
I have tried to work manager to figure out the solution.
private fun setUpWorker(context: Context)
{
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.NOT_REQUIRED).build()
val workRequest =
PeriodicWorkRequest.Builder(DozeWorkManager::class.java,1, TimeUnit.HOURS)
.setConstraints(constraints)
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
LOCAL_NOTIF_WORK,
ExistingPeriodicWorkPolicy.KEEP,
workRequest
)
}
Here running hourly and checking if it's been 24 hours since the last notification was received then I will raise a local notification. The problem with this approach, it is not working in mi and other Chinese devices and sometimes it takes several hours to work again.
I also tried alarm manager.
private fun startAlarm() {
val CUSTOM_INTENT = "com.test.intent.action.ALARM"
val intent = Intent(this@MainActivity, AlarmHelper::class.java)
intent.action = CUSTOM_INTENT
val pendingIntent: PendingIntent =
getBroadcast(this@MainActivity, 101, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(),
System.currentTimeMillis()+60*60*1000, pendingIntent)
}
But it is not working when the app has been removed from the background.
Finally i tried below solution:
private fun startAlert() {
val CUSTOM_INTENT = "com.test.intent.action.ALARM"
val intent = Intent(this@MainActivity, AlarmHelper::class.java)
intent.action = CUSTOM_INTENT
val pendingIntent: PendingIntent =
PendingIntent.getBroadcast(this@MainActivity, 110, intent, PendingIntent.FLAG_CANCEL_CURRENT)
val alarmManager = this@MainActivity.getSystemService(AppCompatActivity.ALARM_SERVICE) as AlarmManager
val info = AlarmManager.AlarmClockInfo(System.currentTimeMillis()+60*60*1000,pendingIntent)
alarmManager.setAlarmClock(info,pendingIntent)
}
This is working fine and tested in mi and realme devices but the problem with this approach is I have to manually do the looping in the receiver function. Like this
override fun onReceive(context: Context?, p1: Intent?) {
setNotification(context)
startAlert(context) // again setting the alarm.
}
The problem with this approach is, it creates a clock icon symbol in the user's device and as per android documentation this might consume battery
I am not sure what approach to follow or Do we have any alternatives? Any kind of help or suggestion will be highly appreciated.