Search code examples
javaandroidandroid-intentandroid-activityandroid-orientation

How to stop android system from redeliver old intent on Orientation Change?


I start an activity A from B with an intent with extras and based on the type of extra in onCreate I do some process and it works fine.

But when I do a orientation change the same old intent is re-delivered by the system to me and the whole process gets restarted since I go through the onCreate once again.

My code completely take care of restoring the previous state of the activity when the onCreate gets called if no old intent is delivered to it. But since the system re-delivers it make my activity think it is a new intent and restarts the whole process once again.

I tried the flag intent.getFlags() != Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY. This flag prevents re-delivery in case of long press home button and activity launched from history but no effect on orientation change.

A dirty fix was proposed in another thread Dirty Fix but I am wondering if there is a proper way to address this problem.

Thanks in advance


Solution

  • A 'clean' solution to this problem would be to use Fragments.

    Create your own Fragment subclass. In its onCreate, be sure to call setRetainInstance(true). In its onCreate you can start your process. If it is just for doing some work, return null in its onCreateView.

    In your Activity's onCreate: - First try to find the current instance of your own Fragment. - If not found, create a brand new one and commit this to your Fragment Transaction.

    By calling setRetainInstance(true) and by first trying to find it before creating a new Fragment in the Activity's onCreate, you keep the same Fragment instance even after a rotation and the Fragment's onCreate won't be called again.