[완벽] Andorid 화면 전환 시 새로고침 방지 ( reload 방지 ) / 자동 회전 / 화면 회전 / 런타임 변경 처리하기

2016. 6. 14. 10:39mobile/android

 

[완벽] Andorid 화면 전환 시 새로고침 방지 ( reload 방지 ) / 런타임 변경 처리하기에 대해서 설명한다.

 

 

 

사진출처 : http://www.samsung.com/sec/home/

 

 

webview 를 사용하는 하이브리드 앱을 만드는데 디바이스의 가로모드를 활성화 하고 화면을 전환하니 갑자기 webview 가 새로고침이 되더라...

 



 

이는 하이브리드 뿐만이 아니라 다른 네이티브 앱들도 비슷한 문제가 있어 보인다.

 

그 화면이 그대로 세로에서 가로로 또는 가로에서 세로로 바뀌게 하고 싶었다.

 

구글링해보니 화면 전환이 일어나면 onCreate 함수가 호출된다는 의견이 꽤 있었다.

 

내가 검색을 못하는 건지 ㅜㅜ 자세한 설명이나 근거가 나와있는 블로그는 없었고 블로그 마다 비슷하지만 다른 설명을 하고 있었다.

 

대충 검색해 보면 매니페스트에 설정을 해야한다는 것 정도는 나와있는데 이 설정정보들에 대한 정확한 정보들은 없었다.

 

설정이라는 것이 모르고 하기에는 찝찝한 부분이 없지않아 있다.

 

다른 블로그들이 완전히 틀린 설명을 하고 있는것은 아니지만 불필요한 설명과 근거 없는 부정확한 짐작에 대한 설명, 타 블로그를 카피한 설명들이 난무했다.

 

나와 같은 초보자들은 혼란스러울 수 있고 잘못된 정보를 학습하게 될 우려가 있어 보였다.

 

필자는 android 초보이고 그렇기 때문에 잘못된 정보를 흡수하고 싶지는 않았다.

 

결국 API 를 뒤지기 시작했다.

 

 

 


API 요약

출처 Andorid API : 링크

 

런타임 변경 ( 화면 방향, 기보드 등 ) 중에 Activity를 다시 시작한다고 한다.

[ onDestroy() 호출 > onCreate() 호출 ]

 

다시 로딩하면서 새로운 기기 구성에 어플리케이션이 적응하는 것을 돕도록 설계되었다고 한다.

 

 런타임 변경 시 자동으로 다시 로딩되지 않고 화면 전환 등의 구성 변경을 직접 처리할 수 있다.

 

직접 구성 변경을 선언하려면 매니페이스 파일의 activity android:configChanges 속성을 추가하면 된다.

 

android:configChanges 에 사용할 수 있는 속성들이 궁금하면 다음 API 문서를 참고

 

가장 많이 사용되는 것은 화면 방향이 변경될 때 다시 시작을 방지하는 orientation 과 키보드 가용성이 변경될 때 다시 시작하는 것을 방지하는 keyboardHidden 이다.

 

다음은 화면 방향 변경과 키보드 가용성 변경을 둘 다 처리하는 선언이다.

1
2
3
<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">
cs

 

 

선언된 구성 중 하나가 변경되더라도 Activity 가 다시 시작되지 않는다. 하지만 onConfigurationChanged()가 호출을 받는다.

 

여기서 직접 구성을 할 수도 있고 생략할 수 도 있다.

 



 

* 주의 : Andorid 3.2 (API 레벨 13) 허니콤 이상부터는 방향 전환이 일어날 경우 화면크기도 같이 변경된다. 따라서 그 이상 버전에서는 screenSize 속성도 함께 추가해야 한다.

 

위 설정을 마친 뒤 설정할 구성이 없다면 onConfigurationChanged() 함수를 구현하지 않으면 된다.

이런 경우는 구성 변경 전에 쓰였던 리소스가 모두 그대로 사용되고 액티비티의 재시작만 회피한 경우에 해당한다.

 

 

 

* 결론 : 다음과 같이 android:configChanges 설정만 해 주면 된다.

1
2
3
<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden|screenSize"
          android:label="@string/app_name">
cs

 

 

 

tip : 반대로 직접 화면 전환이 일어났을 경우를 캐치하고 싶을 수 있다. 그럴 때 위와 같이 선언 한 뒤 onConfigurationChanged() 함수를 구현하면 된다.

 

 

 

 

 

 

 

 

추가 설명 : API 참고

* Configuration Changes

If the configuration of the device (as defined by the Resources.Configuration class) changes, then anything displaying a user interface will need to update to match that configuration. Because Activity is the primary mechanism for interacting with the user, it includes special support for handling configuration changes.

Unless you specify otherwise, a configuration change (such as a change in screen orientation, language, input devices, etc) will cause your current activity to be destroyed, going through the normal activity lifecycle process of onPause(), onStop(), and onDestroy() as appropriate. If the activity had been in the foreground or visible to the user, once onDestroy() is called in that instance then a new instance of the activity will be created, with whatever savedInstanceState the previous instance had generated from onSaveInstanceState(Bundle).

This is done because any application resource, including layout files, can change based on any configuration value. Thus the only safe way to handle a configuration change is to re-retrieve all resources, including layouts, drawables, and strings. Because activities must already know how to save their state and re-create themselves from that state, this is a convenient way to have an activity restart itself with a new configuration.

In some special cases, you may want to bypass restarting of your activity based on one or more types of configuration changes. This is done with the android:configChanges attribute in its manifest. For any types of configuration changes you say that you handle there, you will receive a call to your current activity's onConfigurationChanged(Configuration) method instead of being restarted. If a configuration change involves any that you do not handle, however, the activity will still be restarted and onConfigurationChanged(Configuration) will not be called.

 

* onConfigurationChanged

Added in API level 1
void onConfigurationChanged (Configuration newConfig)

Called by the system when the device configuration changes while your activity is running. Note that this will only be called if you have selected configurations you would like to handle with the configChanges attribute in your manifest. If any configuration change occurs that is not selected to be reported by that attribute, then instead of reporting it the system will stop and restart the activity (to have it launched with the new configuration).

At the time that this function has been called, your Resources object will have been updated to return resource values matching the new configuration.

 

Parameters

newConfig Configuration: The new device configuration.