Search code examples
androidtoast

Should toasts be created using getApplicationContext()?


I was reading over the android documentation for toasts, and noticed that the example code uses getApplicationContext() rather than getActivity() or this. From the docs:

Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();

Based on other sources, I have been given to understand that using getApplicationContext() is generally bad practice. Are toasts somehow an exception? If so, why? Or are the Android docs just wrong in this case?


Solution

  • It's important to note that Toast can be used even when your context is not visible or is not in control of any UI. In other words, the documentation is pointing out that you can have a minimal context (like that from a service) and still use Toast.

    I don't believe that the documentation is trying to present a "best practice" for the use of Context, but rather to properly demonstrate this attribute of Toast.