如何在非活动课使用getSystemService?活动课、如何在、getSystemService

2023-09-04 10:47:50 作者:半世浮生

我建立这将触发通过AlarmManager报警的应用程序。

I am building an application which triggers an alarm via AlarmManager.

我希望能够通过它自己的非活性类拨打了报警,但因为我不是延伸活动,我似乎没有任何背景。这个概念混淆了我,和我读过的SDK文档。

I would like to be able to call the Alarm via it's own non-activity class, but since I am not extending Activity, I don't appear to have any 'context'. This concept confuses me, and I've read the sdk docs.

我会如何使用:

alarmTest = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

在我的非activty类?

in my non-activty class?

另外,我假设得到上下文将允许我使用共享preFS和主意在我的非活性类呢?

Also, I'm assuming getting context will allow me to use SharedPrefs and Intents in my non-activity class as well?

推荐答案

您可以通过上下文这是preferred方式的非活性类或者你可以封装应用程序的基本背景下,以一个单身它可以让您在任何应用程序中访问上下文。在某些情况下,这可能是一个很好的解决方案,但在别人的肯定不是一个好。

You can pass the context to the non-activity class which is the preferred way or you could encapsulate the base context of the application to a singleton which would allow you to access the context anywhere within the application. At some cases this might be a good solution but in others its certainly not a good one.

无论如何,如果你想通过触发报警的 AlarmManager 我是pretty的确认报警要继承从服务 IntentService ,在这种情况下,更好的是你必须通过 this.getBaseContext()获取上下文 this.getApplicationContext()

Anyway, if you want to trigger an alarm via the AlarmManager I'm pretty sure the alarm should inherit from a Service or better yet from IntentService and in such cases you have access to the context via this.getBaseContext() or this.getApplicationContext()