When the face is close to the screen, it goes black; when it's farther away, the screen lights up.
Having it while making a call can prevent accidental touches.
However, I couldn't find any relevant code after searching the entire Flutter organization.
So I plan to do it myself⬇️
Android#
In Android, before API 21, you had to manually write the proximity sensor and screen on/off functions.
After API 21, which is Android 5.0, PowerManager added a new constant
PROXIMITY_SCREEN_OFF_WAKE_LOCK
Making this functionality very simple to implement.
if ((pm.getSupportedWakeLockFlags()
& PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) != 0x0) {
mProximityWakeLock = pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, LOG_TAG);
}
iOS#
In iOS, there are also corresponding methods to implement this.
// The implementation of the proximity sensor is encapsulated in UIKit
// Requires testing on a real device
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// The system app automatically enables proximity detection (e.g., during calls, when the face is close to the screen, it goes black; when farther away, the screen lights up)
// But developer apps need to enable it manually
UIDevice.current.isProximityMonitoringEnabled = true
// Use notifications to listen for distance changes
NotificationCenter.default.addObserver(self, selector: #selector(proximityStateChanged), name: NSNotification.Name.UIDeviceProximityStateDidChange, object: nil)
}
@objc private func proximityStateChanged(){
if UIDevice.current.proximityState == true{ // Close distance
print("Too close, it's right on my face")
// Lock the screen at close distance, making it go black to save power
UIApplication.shared.isIdleTimerDisabled = false
} else{ // Far distance
print("Too far, I can't see you")
// Do not lock the screen at far distance
UIApplication.shared.isIdleTimerDisabled = true
}
}
}
Both platforms have implementation methods, and we just need to create a Plugin to integrate it into our own project.