Hootsuite Sep 3, 2015

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

Critical Insight

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.

The article reveals a specific pattern using retained Fragments and interface callbacks that lets AsyncTasks survive orientation changes without leaking memory.

About This Article

Problem

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.

Solution

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.

Impact

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.