I'm developing a simple tasks app in Android and I need to create notifications via an AlarmManager. My problem is that I have certain alarms that should be deleted -and thus their notifications- but they aren't, so I decided -following posts such as Delete alarm from AlarmManager using cancel() - Android to make the AlarmManager a static variable so the same instance can be reached from the whole app. The way I'm doing this is having the following method in my main class:
public static AlarmManager getAlarmManagerInstance() {
if (sAlarmManager == null && sContext != null)
sAlarmManager = (AlarmManager) sContext
.getSystemService(Context.ALARM_SERVICE);
return sAlarmManager;
}
and in the the sContext
variable will be instantiated this way:
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
sContext = this;
initActionBar();
}
Is it a good idea to create a singleton pattern from this variable? Is there any better approach?
Thanks a lot in advance.
Android documentation says:
You do not instantiate this class directly; instead, retrieve it through Context.getSystemService(Context.ALARM_SERVICE).
AlarmManager is just a class that provides access to the system alarm services.
This services are running in the system so don't care about them just use AlarmManager as an interface to interact with them.
So each time that you need to access to this service just retrieve it as the documentation says:
Context.getSystemService(Context.ALARM_SERVICE)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With