Android: Help handle screen orientation change

心已入冬 提交于 2019-12-22 11:29:33

问题


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!


回答1:


You should use a background service for the timer, so that it doesn't stop on orientation change.




回答2:


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"



回答3:


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. :)




回答4:


Use this:

android:configChanges="orientation|keyboard"

Example:

<activity android:name=".HomeActivity" android:configChanges="orientation|keyboard" />



回答5:


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



来源:https://stackoverflow.com/questions/9339224/android-help-handle-screen-orientation-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!