Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Switching orientation with threads
I have an app that runs a threads in the background of just about every view. When the user switches the orientation, the view loads again and the thread post back to the old view that isn't there anymore. How do I take care of this problem? How do I make the thread post to the most recent main view? iOS doesn't do this :P
Ben JakubenTreehouse Teacher
When you switch orientation in Android, the Activity is destroyed and created again, so
onCreate() runs again. It's kind of a pain. You need to be careful to not start those background threads a second time.
Now, for the running background threads, one trick is to use a Fragment inside the Activity that you can retain and reuse even if the parent Activity is destroyed. Here's an article that talks about it with sample code: http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html
By default, Fragments are destroyed and recreated along with their parent Activities when a configuration change occurs. Calling
Fragment#setRetainInstance(true)allows us to bypass this destroy-and-recreate cycle, signaling the system to retain the current instance of the fragment when the activity is recreated. As we will see, this will prove to be extremely useful with Fragments that hold objects like running Threads, AsyncTasks, Sockets, etc.