which context to use in service?

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

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?

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!