简体   繁体   中英

How to get Application from Context

Is there a way I can get application from Context. I noticed that activity and service has getApplication() method but Context does not.

Background:

I am using/extending the GCMBaseIntentService and the

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

Thanks

Context#getApplicationContext将返回您的Application实例。

val application : Application = context.applicationContext as Application

For those looking for an answer in 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)
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM