Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static AlarmManager in Android

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.

like image 792
noloman Avatar asked Nov 01 '22 16:11

noloman


1 Answers

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)

like image 91
Manolo Garcia Avatar answered Nov 09 '22 15:11

Manolo Garcia