Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which context to use in service?

Tags:

android

I want to call method in some other class which need Context as input parameter but i have 3 possibility in service:

- getApplicationContext
- getBaseContext
- getApplication

Which one to use in ScreenService which extends Service

what is the main different. I read some times ago that is not good to use getApplicationContext. Is that true?

like image 774
senzacionale Avatar asked Dec 01 '12 08:12

senzacionale


1 Answers

Application context is attached to the application's life-cycle and will always be same throughout the life of application. So if you are using Toast, you can use application context or even activity context (both) because a toast can be raised from anywhere with in your application and is not attached to a window.

Activity context is attached to the Activity's life-cycle and can be destroyed if the activity's onDestroy is raised.

getApplication() though its referring to Application object but the Application class extends Context class, so it can be used to offer application context.

getApplicationContext() offers application context.

getBaseContext() offers activity context.

It depends why you for which purpose you are using the context,

getApplicationContext() is most preferred way since this Context lives untill Application shuts down.

getBaseContext() Context is available to widgets and Views.

so in a toast message or when creating an intent, they all have the same effect eventhough using getApplicationContext() is the most correct. Toast accepts any kind of Context since its not attached any kind of View. Its a notification.

like image 94
Sahil Mahajan Mj Avatar answered Oct 03 '22 09:10

Sahil Mahajan Mj