Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toast.makeText() - activity or application context

I've read a couple of discussions on when to use activity and when to use application context (e.g. on this SO post).

I'm wondering what the implications of using either activity or application context are for the method Toast.makeText().

The documentation only briefly says for parameter context:

Context: The context to use. Usually your Application or Activity object.

My questions are

  • When using the activity context is the toast's duration bound to the activity lifecycle?
  • Are memory leaks a serious issue here? They seem to be limited by the duration of the toast.

What else is to be considered?

like image 533
Peter F Avatar asked Oct 13 '17 13:10

Peter F


People also ask

What is toast in mobile application development?

Andorid Toast can be used to display information for the short period of time.

What is toast and toast method What are its three parameters and display method?

Create a Toast in Android The makeText() method will take three parameters: application context, text message and the duration for the toast. We can display the Toast notification by using show() method. Following is the syntax of creating a Toast in android applications. It's our application context.


1 Answers

I would just use Application context. Using your Activity context means a reference to your Activity will likely stay alive until the Toast stops displaying, which might delay garbage collection by a few seconds.

When using the activity context is the toast's duration bound to the activity lifecycle?

I didn't look at the source code but I would say it is the opposite: your activity reference will stay until your Toast stops being displayed.

Are memory leaks a serious issue?

Yes they are ! In this case, it won't be a leak forever since the reference to the activity will eventually be garbage collected. You will use more memory than strictly needed for a few seconds so ApplicationContext is safer. And in all cases, I don't see a real downside of using the ApplicationContext here.

like image 75
mbonnin Avatar answered Sep 28 '22 19:09

mbonnin