I'm making a simple timer as a part of an Android app using a handler to call a runnable which updates the UI. However, when the user changes the screen orientation, the app restarts. I looked into onSaveInstanceState(), but that won't help me.
I notice that some video player apps continue to play video during screen orientation change. Is it possible to similarly keep my activity running? I don't want my timer to stop running when the user tilts their phone.
Any ideas on how to fix this? (apart from fixing the screen orientation)
Thanks!
You should use a background service for the timer, so that it doesn't stop on orientation change.
Im not sure even i have faced this issue but i prefer to do this, include this in your manifests respective activity stub.
android:configChanges="orientation|keyboardHidden"
If you want to fix your orientation to landscape/portrait then use this code:
<activity android:name=".MainMenuActivity" android:screenOrientation="landscape" android:configChanges="keyboard|keyboardHidden|orientation" />
or just want to handle the situstion even if the orientation change then try this:
<activity android:name=".MainMenuActivity" android:configChanges="keyboard|keyboardHidden|orientation" />
Hope it will solve your problem.
Enjoy. :)
Use this:
android:configChanges="orientation|keyboard"
Example:
<activity android:name=".HomeActivity" android:configChanges="orientation|keyboard" />
You can override onPause() and onResume() to handle these events.
onPause() fires right before the orientation change(or at the very start of it) and onResume rigth after(or at the very end of it).
If you use this approach you can save your data with SharedPreferences.
You can also save your data using onSaveInstanceState() and onRestoreInstanceState() which might be a better approach.
Android activity lifetime
SharedPreferences
InstanceState