在Android的静态AlarmManager静态、Android、AlarmManager

2023-09-07 23:11:12 作者:﹊默小壹﹎

我正在开发Android中一个简单的任务的应用程序,我需要通过AlarmManager创建通知。我的问题是,我有一定的报警应删除-and因而其通知 - 但他们都没有,所以我决定-following职位,如Delete使用取消()从AlarmManager报警 - Android电子使AlarmManager一个静态变量,以便同一个实例可以从整个应用程序即可到达。我这样做的方式是有我的主类下面的方法:

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;
    }

和在该 sContext 变量将被实例化这种方式:

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?

非常感谢在前进。

推荐答案

Android文档说:

Android documentation says:

您不要直接实例化这个类;相反,通过Context.getSystemService(Context.ALARM_SERVICE)检索它。

You do not instantiate this class directly; instead, retrieve it through Context.getSystemService(Context.ALARM_SERVICE).

AlarmManager只是提供对系统报警服务的访问类。

AlarmManager is just a class that provides access to the system alarm services.

这个服务在系统中运行,所以不计较他们只需使用AlarmManager作为一个接口来与它们进行交互。

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)

Context.getSystemService(Context.ALARM_SERVICE)