Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to differentiate between ApplicationContext and Context?

Tags:

java

android

I have a Android method which receives instance of Context object, I want to differentiate if the passed context object is returned using one of the following methods

  • View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity.

  • Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.

Since both methods return instance of Context object but with different capabilities, how can I differentiate if passed context object is Activity Context or Application Context ?

like image 695
Pradeep Avatar asked Feb 09 '23 19:02

Pradeep


1 Answers

Since both methods return instance of Context object but with different capabilities, how can I differentiate if passed context object is Activity Context or Application Context ?

you can check with instanceof. It allows to check if the object is of a certain type. E.g.

 if (context instanceof Activity) {

 } 
like image 154
Blackbelt Avatar answered Feb 11 '23 16:02

Blackbelt