Toast.makeText() - activity or application context
Asked Answered
S

1

9

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?

Subvert answered 13/10, 2017 at 13:8 Comment(1)
Memory leaks are a serious issue. If you waste memory you can risk not having enough memoryHousecarl
R
13

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.

Rutger answered 13/10, 2017 at 13:10 Comment(1)
Thanks for your answer. The only reason to use activity context would have been if the toast's lifetime had been bound to the activity lifetime. Since that does not seem to be the case, I completely agree.Subvert

© 2022 - 2024 — McMap. All rights reserved.