I want to wake an activity on a specific time. To do so, I (also) registered AlarmManager on a Boot complete BroadcastReceiver.
As far as I know, only the Service can last forever to be alive in the background to wake an Activity. Activities and BroadcastReceiver can die on inactivity.
The following code I have doesn't run a service. However, it seems like it's working (Alarm works even if I launch it after 24 hours). Is this safe? Or should I launch a service? If this is safe to use, what's the logic behind this? why is AlarmManger created by BroadcastReceiver doesn't get destroyed by Android lifecycle manager?
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
registerAlarm(context);
}
}
private void registerAlarm(Context context)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am =(AlarmManager)context.getSystemService(Activity.ALARM_SERVICE);
long nextAlarm = System.currentTimeMillis() + 10000; //Some time later.
am.set(AlarmManager.RTC_WAKEUP, nextAlarm, pendingIntent);
}
}
Is this safe?
AlarmManager
does not care what sort of PendingIntent
you use.
Users may or may not appreciate an activity appearing out of nowhere, but that is a separate issue.
As far as I know, only the Service can last forever to be alive in the background to wake an Activity.
Services do not last forever.
Activities and BroadcastReceiver can die on inactivity.
No. Your process can "die on inactivity", which includes all components in that process.
why is AlarmManger created by BroadcastReceiver doesn't get destroyed by Android lifecycle manager?
Because AlarmManager
is a system service, maintained by the OS, not by your app.