2

I have the util class to get the devices rotation (example below). It operates over application context. When I have phone in portrait mode, it returns PORTRAIT. However, when I rotate phone to landscape, then this method still returns PORTRAIT.

The same thing happens when I have values and values-land with a boolean flag indicating landscape that I read on demand.

It looks like that application context's configuration remains the same through the whole process lifetime. E.g. it keeps the configuration it started with.

Can anybody confirm this please? And if so, how should I approach this issue?

@Singleton
class DeviceInfo @Inject constructor(private val context: Context) {

    enum class DeviceOrientation {
        PORTRAIT, LANDSCAPE
    }

    fun getOrientation(): DeviceOrientation {
        val orientation = context.resources.configuration.orientation
        return when (orientation) {
            Configuration.ORIENTATION_LANDSCAPE -> DeviceOrientation.LANDSCAPE
            else -> DeviceOrientation.PORTRAIT
        }
    }
}
bakua
  • 13,704
  • 7
  • 43
  • 62
  • When you are creating the instance of DeviceInfo you are saving the current context in a static, and this is not changing. Try to pass the context as an argument in your funcion. – Alvaro Mar 05 '19 at 14:06
  • I understand that, but Context should be passed by a refference. Since this context is just an application casted to context, it should be always the same instance, no matter how I pass it. AFAIK the application context instance cannot possibly change during the process lifetime as it would mean that the Application class gets recreated. – bakua Mar 05 '19 at 19:30
  • how are you providing that context in your graph? – Alvaro Mar 07 '19 at 12:08
  • With dagger. It's a singletone scoped provided application that is typecasted to Context. – bakua Mar 08 '19 at 08:48

0 Answers0