[英]How to get Application from Context
Is there a way I can get application from Context.有没有办法可以从 Context.Application 中获取应用程序? I noticed that activity and service has getApplication() method but Context does not.
我注意到活动和服务有 getApplication() 方法,但 Context 没有。
Background:背景:
I am using/extending the GCMBaseIntentService and the我正在使用/扩展 GCMBaseIntentService 和
protected abstract void onMessage (Context context, Intent intent)
gives me a context as a parameter.给我一个上下文作为参数。 I would like to get the Application object so I can downcast it to MyApplication and retrieve some variables
我想获取 Application 对象,以便我可以将其向下转换为 MyApplication 并检索一些变量
Thanks谢谢
Context#getApplicationContext
将返回您的Application
实例。
val application : Application = context.applicationContext as Application
For those looking for an answer in kotlin:对于那些在 kotlin 中寻找答案的人:
@BindingAdapter("app:setSelectArea")
@JvmStatic
fun setSelectArea(view: ImageView, mContext: ContextX){
view.setOnClickListener {
val application = view.context.applicationContext as Application
val viewModel:KnowledgeViewModel by lazy { KnowledgeViewModel(application) }
val mKnowledge = Knowledge(
"",
"abcdefg test",
""
)
viewModel.firebaseInsertKnowledge(mKnowledge)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.