0

I want to be able to set a variable alarm from the background whenever my service is run. I am using the following code:

...
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        ...
        Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
        i.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
        i.putExtra(AlarmClock.EXTRA_HOUR, 9);
        i.putExtra(AlarmClock.EXTRA_MINUTES, 9);
        i.putExtra(AlarmClock.EXTRA_MESSAGE, "Good Morning");
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
    }
...

I am aware that an activity cannot be started from the background. But is there any other way or a hack to be able to accomplish what I need to do here?

fsljfke
  • 431
  • 6
  • 14

1 Answers1

2

Looking at Schedule Repeating Alarms documentation, you could use AlarmManager with a PendingIntent as seen below.

When you start the service, you could always set up the alarm and set the alarm to trigger straight away using the current time.

When the alarm goes off, it sends out a intent to a Broadcast Reciever (which is AlarmReceiver in the case below - just make your own). You can then do whatever you want from AlarmReceiver.

It is probably worth running through the full documentation as I found it super useful. It will only take maximum 15 minutes, is really clear and it should meet your requirement.

private var alarmMgr: AlarmManager? = null
private lateinit var alarmIntent: PendingIntent
...
alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmIntent = Intent(context, AlarmReceiver::class.java).let { intent ->
    PendingIntent.getBroadcast(context, 0, intent, 0)
}

// Set the alarm to start at 8:30 a.m.
val calendar: Calendar = Calendar.getInstance().apply {
    timeInMillis = System.currentTimeMillis()
    set(Calendar.HOUR_OF_DAY, 8)
    set(Calendar.MINUTE, 30)
}

// setRepeating() lets you specify a precise custom interval--in this case,
// 20 minutes.
alarmMgr?.setRepeating(
        AlarmManager.RTC_WAKEUP,
        calendar.timeInMillis,
        1000 * 60 * 20,
        alarmIntent
)
  • Calum, can you please help with [this one](https://stackoverflow.com/q/63431995/5993712)? I am trying to cancel an intent set by myself. – fsljfke Aug 16 '20 at 00:35