Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinguish if given Context object is an Activity or a Service Context?

Tags:

android

I would like to know if my given Context object is from Activity, Service or Application. Or in other words if my code is executing in background or in foreground. (By foreground i mean Activity code and threads that have been created by Activity.)

like image 267
Michal Chudy Avatar asked Jan 04 '11 18:01

Michal Chudy


People also ask

What is difference between activity context and application context?

Application Context: It is the application and we are present in Application. For example - MyApplication(which extends Application class). It is an instance of MyApplication only. Activity Context: It is the activity and we are present in Activity.

What is the difference between activity and context?

In android, Context is the main important concept and the wrong usage of it leads to memory leakage. Activity refers to an individual screen and Application refers to the whole app and both extend the Context class.

How do I find the context of an object?

To access the context object, first specify the parameter name by appending . $ to the end, as you do when selecting state input with a path. Then, to access context object data instead of the input, prepend the path with $$. .


1 Answers

You should be able to test if an object is a specific class using "instanceof"

if (context instanceof Activity) {
  // handle activity case
} else if (context instanceof Service){
  // handle service case
}
like image 191
danh32 Avatar answered Oct 20 '22 15:10

danh32