Get Context in a Service

安稳与你 提交于 2020-01-08 14:01:26

问题


Is there any reliable way to get a Context from a Service?

I want to register a broadcast receiver for ACTION_PHONE_STATE_CHANGED but I don't need my app to always get this information, so I don't put it in the Manifest.

However, I can't have the broadcast receiver be killed by the GC when I need this information so I'm registering the broadcast receiver in a Service.

Hence, I need a Context to to call registerReceiver(). When I no longer need the ACTION_PHONE_STATE_CHANGED I unregister it.

Any tips?


回答1:


Service is a Context




回答2:


Service extends ContextWrapper which extends Context. Hence the Service is a Context. Use 'this' keyword in the service.




回答3:


  1. Service extends ContextWrapper
  2. ContextWrapper extends Context

So....

Context context = this;

(in Service or Activity Class)




回答4:


Since Service is a Context, the variable context must be this:

DataBaseManager dbm = Utils.getDataManager(this);   



回答5:


As Service is already a Context itself

you can even get it through:

Context mContext = this;

OR

Context mContext = [class name].this;  //[] only specify the class name
// mContext = JobServiceSchedule.this; 


来源:https://stackoverflow.com/questions/6446221/get-context-in-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!