Search code examples
androidtoast

Toast not showing on progressUpdate in android 6 when using getApplicationContext() as context


I´m trying to show a Toast on ProgressUpdate() method. Works well on Android 4,5 but the toast is not shown on android 6 and no exceptions are thrown.

Here is my method:

@Override
    protected void onProgressUpdate(String... values) { 
    super.onProgressUpdate(values);
    Toast.makeText(getApplicationContext(), values[0],     Toast.LENGTH_SHORT).show();
    }

If I replace getApplicationContext() with getBaseContext(), the Toast works as expected.

It does not work if I use MainActivity.this as context

Is it correct to use getBaseContext() ? Why works with getApplicationContext() on android 4,5 and not on 6?


Solution

  • I'm not sure what happened when they made the Android 6.0 update, but they must have wrapped some contexts, or something like that. Here's the difference between those two methods: Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

    Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.

    ContextWrapper.getBaseContext(): If you need access to a Context from within another context, you use a ContextWrapper. The Context referred to from inside that ContextWrapper is accessed via getBaseContext().