Android : Identify device state

37 views Asked by At

I am new to Android, facing issue with background tasks. I want to know, is there any way to find out if the device has gone into doze mode or came out of doze mode or the current state of the device? I referred this, but this did not work.

Please guide. Thanks in advance.

1

There are 1 answers

0
ΓDΛ On

Yes there is. You can use the extension function, which I often use in my own projects. Since the code was very understandable, I did not need to explain it.

fun Context.getDozeState(): DozeState {
    val powerManager = powerManager ?: return DozeState.ERROR_GETTING_STATE
    return if (powerManager.isDeviceIdleMode) DozeState.DOZE_TURNED_ON_IDLE else if (powerManager.isInteractive) DozeState.NORMAL_INTERACTIVE else DozeState.NORMAL_NON_INTERACTIVE
}

enum class DozeState {
    NORMAL_INTERACTIVE, DOZE_TURNED_ON_IDLE, NORMAL_NON_INTERACTIVE, ERROR_GETTING_STATE, UNKNOWN_TOO_OLD_ANDROID_API_FOR_CHECKING
}