Search code examples
androidkotlinscreencallwakelock

How to turn screen off based on proximity sensor?


The original idea is to recreate the basic phone behaviour that turn screen off when you are near the phone and turn it back on when you are far when making a call.

I’ve spent a lot of time trying to answer this question without finding any simple solution and I believe answering it here might help some people. I won’t show how to deal with calls state as this solution allows you to enable/disable the behaviour when you want.


Solution

  • An example project can be found here on GitHub

    First you need to declare that you are using Wakelock in AndroidManifest.xml :

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    

    Then in your activity import PowerManager

    import android.os.PowerManager
    

    Declare your attributes

    private lateinit var powerManager: PowerManager
    private lateinit var lock: PowerManager.WakeLock
    

    In onCreate method instantiate them : (replace "simplewakelock:wakelocktag" with another unique tag)

    powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
    lock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK,"simplewakelock:wakelocktag")
    

    Then you can enable and disable the lock (and the behaviour) using :

    // Enable : Acquire the lock if it was not already acquired
    if(!lock.isHeld) lock.acquire()
    
    // Disable : Release the lock if it was not already released
    if(lock.isHeld) lock.release()
    

    Just put it where you want and don’t forget to release the lock when you don’t need it anymore (onPause can be a good place), otherwise it will continue even if you switch app.