

The class MakeMyToast is the example service we have running which it just makes a toast every time it runs. The method setAlarm is the one actually setting the alarm to occur in 15 seconds, which when it is being triggered the onReceive method creates a new Intent for the MakyMyToast class and re-sets the alarm so it will run again after 15 seconds. PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0) Īm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis()/1000L + 15L) *1000L, pi) //Next alarm in 15s

Intent i = new Intent(context, AlarmReceiver.class) Intent in = new Intent(context, MakeMyToast.class) ĪlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE) Public class AlarmReceiver extends void onReceive(Context context, Intent intent) Lets see the source of the class that creates the alarm: package The trick is that every time the alarm goes off, we set it again 15 seconds later! We are going to create now a background service which runs every 15 seconds and makes a toast for us! The idea is the following: instead of creating a repeating alarm which does not respect the 15 second limit we create an exact alarm that is allowed with the idle state. The proposed way for something like that to be done for a marketplace application is through the Work Manager. So as you can imagine in this article I am presenting you the solution that worked reliably according to the requirements we set.īefore moving on I would like to emphasize that this solution by NO means should be included in an application heading for a marketplace as it will probably have negative impact on the battery and user experience. The second problem was that the background service needs to run even if the phone is in an idle state or if the application gets killed. Take for example the repeating alarm, it turned out that after some time it no longer respect the 15 seconds but runs at an arbitrary amount of time decided by the android system. Although these requirement may not seem much to someone with some knowledge on Android development it turned out that this is not as trivial as initially thought! Upon googling about it you will find many different ways that you could run a service in the background every some seconds, like set a repeating alarm ! There are basically two problems that discovered with these ways, first is that they are not always exact. In the context of an experiment I am running, it was required to run a background service where it is supposed to run every 15 seconds and not to stop even if the device is idle.
