如何在非活动课使用getSystemService? [英] How to use getSystemService in a non-activity class?
问题描述
我建立这将触发通过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()
这篇关于如何在非活动课使用getSystemService?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!