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
What else is to be considered?
Andorid Toast can be used to display information for the short period of time.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With