1

After painfully finding out that Typeface.createFromAsset can create memory leaks, I am trying to find a full workaround. The caching solution described in the above link helps to avoid having to reload fonts repeatedly while the application is running. But how about cases where your app has to start again from onCreate (e.g., after orientation changes, other apps popping up in between etc.)? Is there any way to store the typeface(s) in onSaveInstanceState in order to avoid having to call again Typeface.createFromAsset and leaking memory every time?

Community
  • 1
  • 1
urps
  • 366
  • 1
  • 4
  • 13
  • 1
    The cache solution from the link will still work. If your app has to start again, it will either _1)_ create a new process and re-cache the fonts or _2)_ re-use the cached fonts. The key here is that the cache is declared as `static`. – pathfinderelite Nov 06 '16 at 16:48
  • Thanks. So this means that either all memory will be freed anyway, since the activity is gone completely, or the static cache is still alive when onCreate is called again? --- In my case, which is actually much simpler in using just a single font (i.e., no caching needed, if I just store this single Typeface as a field for my main activity), would the solution be simply to declare this Typeface field static? Or could this lead to other problems/memory leaks? – urps Nov 06 '16 at 17:06
  • 1
    Yes, just use a static field to store your Typeface. The only memory "issue" is that your Typeface will stay in memory for the duration of your process, but this isn't really a problem at all, especially since its just _one_ typeface. Also, while I don't think that `Typeface` maintains an internal reference to the context used to create it, just to be safe, you may want to use `context.getApplicationContext()` when calling `createFromAsset` to avoid any potential context leak. – pathfinderelite Nov 06 '16 at 17:13

0 Answers0