I am trying to develop an alarm system in android that would function after the application closes, making multiple simultaneous alarms possible (which should be repeatable and cancelable, but I have read documentation for such functions).
Currently, I only have the UI (which fires off intents to receiver at scheduled times through AlarmManager) and the Receiver class (which extends BroadCastReceiver). Although the alarm somehow functions, there have been issues like the alarm not sounding at appropriate times until I open app again and not providing the correct alarm.
I have read that a service is commonly used in such apps to provide functionality of the application when the activity is closed. Thus, I am interested in what a service would provide in the context of the application, and whether my problems are solvable through service.
I have searched answers and read that a service is useful for running background operations (i.e. mp3 or alarm) For example, google states that "Another application component can start a service and it will continue to run in the background even if the user switches to another application. ". The following answer states that to use "alarm simultaneously you must use Service class for that".
Therefore, I think that a service may be useful for providing the functionality for the alarm. However, some people seem to represent a service as a either or with AlarmManager, which I am currently using. Most others seem to use AlarmManger to start service or perform an action of that nature. I would be very grateful if someone could shed light on what a service provides (I've already read google's explanation but it did not clear up whether I need it or not). Sending intent from UI
if (row.get(7) == 1) {
Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
alarmIntent.putExtra("id", (long) row.get(0));
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
long longValue = (long) row.get(0);
int intValue = (int) longValue;
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, intValue, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
if (row.get(8) == 1) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, (long) row.get(6), (long) row.get(9), pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, (long) row.get(6), pendingIntent);
}
}
AlarmReceiver class
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
long id = intent.getLongExtra("id", 0);
Notification.Builder builder = new Notification.Builder(context)
.setSmallIcon(R.drawable.ic_action_search)
PendingIntent pi = PendingIntent.getActivity(context, (int)id, new Intent(), 0);
NotificationManager nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify((int)id, builder.build());
}
}