Handling Orientation Changes on Android
Article Summary
Android orientation changes are one of the most frustrating challenges for mobile engineers. When users rotate their device, Android destroys and recreates your Activities and Fragments, wiping out all member variables in the process.
Hootsuite's engineering team breaks down the proper way to handle screen rotations on Android. This deep dive covers the lifecycle callbacks, state management patterns, and common pitfalls that lead to memory leaks and crashes.
Key Takeaways
- Avoid configChanges flag: prevents resource reloading and alternate layouts
- Save state in onSaveInstanceState, restore in onCreate or onActivityCreated
- Use retained Fragments to host AsyncTasks and prevent task cancellation
- Memory leaks occur when AsyncTasks hold references to destroyed Activities
- Check savedInstanceState for null before instantiating Fragments to avoid duplicates
Proper orientation handling requires saving state before destruction, restoring it after recreation, and using retained Fragments for long-running tasks to avoid memory leaks and crashes.
About This Article
AsyncTasks can cause WindowLeaked exceptions and IllegalArgumentExceptions when ProgressDialogs are dismissed after the screen rotates. This often crashes apps once the task finishes on an Activity that no longer exists.
Hootsuite Engineering suggests cancelling AsyncTasks in onDestroy, storing task state in onSaveInstanceState, or using retained Fragments with listener interfaces to keep UI updates separate from task lifecycle.
Retained Fragments that host AsyncTasks stop tasks from restarting when the screen rotates. This prevents downloads from interrupting and keeps file transfers working smoothly across orientation changes.