static AlarmManager in Android

2019-06-23 17:11发布

问题:

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.

回答1:

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)



回答2:

I would advise against creating a static Alarm.

You should follow the advice given in the comments, to use IDs given to your PendingIntents, this way you can cancel/update your alarms surely from any place within your application.

Reason why i advised against static Alarm:

The following scenario can occur, you schedule the alarm and make a static reference to it, then the user reboots the phone. Your alarm is gone and so is the static reference to it.

If you need your alarms to work in such scenario, you should write their ids and required info in shared preferences/database/file and reschedule them onBoot or on some other event suitable for your app.