View Full Version : فرق بین getContext , getApplicationContext و .... ؟؟
mahdi2elve
دوشنبه 02 شهریور 1394, 12:53 عصر
سلام مهندسین گرامی
میخاستم فرق بین
getContext
getApplicationContext
getBaseContext
getApplication
this
رو بدونم؟
اگه امکانش هست توضیح کوتاه و قابل فهمی از هر یک ارائه بدین. جهت اهداف اموزشی نیاز دارم.
mahdi2elve
دوشنبه 02 شهریور 1394, 18:21 عصر
مهندسین نیستین جواب بدین؟
morycom
یک شنبه 11 مهر 1395, 09:12 صبح
مهندسین نیستین جواب بدین؟
Very interesting question. I think it's mainly a semantic meaning, and may also be due to historical reasons.
Although in current Android Activity and Service implementations, getApplication() and getApplicationContext() return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation).
So if you want the Application class you registered in the Manifest, you should never call getApplicationContext() and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).
Why does getApplicationContext() exists in the first place ?
getApplication() is only available on the Activity class and in the Service class, whereas getApplicationContext() is declared in the Context class.
That actually means one thing : when writing code in a broadcast receiver, which is not a context but is given a context in its onReceive method, you can only call getApplicationContext(). Which also means that you are not guaranteed to have access to your application in a BroadcastReceiver.
When looking at the Android code, you see that when attached, an activity receives a base context and an application, and those are different parameters. getApplicationContext() delegates it's call to baseContext.getApplicationContext().
One more thing : the documentation says that it most cases, you shouldn't need to subclass Application:
There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.
I know this is not an exact and precise answer, but still, does that answer your question?
tux-world
یک شنبه 11 مهر 1395, 23:39 عصر
خوب من فهمیدم. بقیه چی؟ الان نمیشه که بشینیم ما ترجمه کنیم این رو. بهتر نبود از اول فارسی مینوشتید. اینا که اگه انگلیسیشون خوب بود اینجا که نمیپرسیدن دوست عزیز
vBulletin® v4.2.5, Copyright ©2000-1404, Jelsoft Enterprises Ltd.