Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Very interesting question. I think it's mainly a semantic meaning, and may also be due to historical reasons.</p> <p>Although in current Android Activity and Service implementations, <code>getApplication()</code> and <code>getApplicationContext()</code> return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation).</p> <p>So if you want the Application class you registered in the Manifest, you should <strong>never</strong> call <code>getApplicationContext()</code> and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).</p> <p>Why does <code>getApplicationContext()</code> exist in the first place ?</p> <p><code>getApplication()</code> is only available in the Activity class and the Service class, whereas <code>getApplicationContext()</code> is declared in the Context class.</p> <p>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 <code>getApplicationContext()</code>. Which also means that you are not guaranteed to have access to your application in a BroadcastReceiver.</p> <p>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. <code>getApplicationContext()</code> delegates it's call to <code>baseContext.getApplicationContext()</code>.</p> <p>One more thing : the documentation says that it most cases, you shouldn't need to subclass Application: </p> <blockquote> <p>There is normally no need to subclass <code>Application</code>. 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 <code>Context</code> which internally uses <code>Context.getApplicationContext()</code> when first constructing the singleton.</p> </blockquote> <p>I know this is not an exact and precise answer, but still, does that answer your question?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload