36

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

Snake
  • 14,228
  • 27
  • 117
  • 250

3 Answers3

31

Context#getApplicationContext will return your Application instance.

Egor Neliuba
  • 14,784
  • 7
  • 59
  • 77
  • 8
    How so? The docs say that it will return "the **context** of the single, global Application object of the current process." The return type is `Context`, not `Application`. `Context` is an ancestor class of `Application`, but how do you know that `getApplicationContext()` will return the `Application` instance? I suspect you may be right, but I'd like to see an authoritative source that agrees. – LarsH Oct 25 '17 at 15:10
  • 11
    See for example https://stackoverflow.com/questions/5018545/getapplication-vs-getapplicationcontext which says that `getApplicationContext()` will **not** always return the same object as your `Application` instance. – LarsH Oct 25 '17 at 15:23
  • 11
    Is this even a correct answer? Why is it accepted and upvoted so much? – Tanasis Dec 04 '18 at 15:37
  • 7
    I can't find a statement confirming my answer, but at least the Google devs [use this method in AndroidX](https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/lifecycle/lifecycle-process/src/main/java/androidx/lifecycle/ProcessLifecycleOwner.java?source=post_page---------------------------%2F&autodive=0%2F#162) – Egor Neliuba Aug 27 '20 at 11:40
10
val application : Application = context.applicationContext as Application
eggham0518
  • 121
  • 1
  • 7
0

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)
            }
        }
byteman
  • 101
  • 1