Handling Configuration Changes with Fragments
This post addresses a common question that is frequently asked on StackOverflow:
What is the best way to retain active objects—such as running
Thread
s,Socket
s, andAsyncTask
s—across device configuration changes?
To answer this question, we will first discuss some of the common difficulties developers face when using long-running background tasks in conjunction with the Activity lifecycle. Then, we will describe the flaws of two common approaches to solving the problem. Finally, we will conclude with sample code illustrating the recommended solution, which uses retained Fragments to achieve our goal.