Reputation: 993
In Android land, Fragments are aware of the Android lifecycle and are not destroyed when an activity is recreated. Because of this, I have seen people using empty fragments to get around issues with the Android lifecycle destroying references to background tasks and prevent leaks associated with keeping references to activities.
I was wondering how much overhead is associated with using Fragments as hooks to background tasks? I assume that Android decides not to destroy fragments because they are expensive to recreate (could be wrong).
Bonus question. Is there a way we can measure this cost? (maybe implementing alternate methods and checking resource utilisation).
Upvotes: 1
Views: 384
Reputation: 7749
Do not use Fragment
s to keep tasks alive!
That will do more harm than use.
If you have tasks running long enough that you have to worry if they get killed, run them in a Service
.
This is exactly what a Service
(or Loader
) is for. Fragment
s should represent a part of your layout, not be used headless.
There is no reason to hack around if a working and intended solution exists.
Upvotes: 1
Reputation: 3916
You should not use a 'headless fragment' for background work.
The correct way is to use a Loader
or Service
(or Intent Service
) depending on the duration and type of work that needs to be done.
In terms of overhead, I don't think there is much. You can create 4 apps with these 4 methods and profile them if you want, but the better approach is to pick a method that works for the problem you are trying to solve.
Upvotes: 1