When close to the face, the screen goes black; when away, the screen lights up.
Having it while on a call can prevent accidental touches.
However, I couldn't find any related code after searching the entire Flutter organization.
So I plan to do it myself ⬇️
Android#
In Android, before API 21, you need to manually write the proximity sensor and screen on/off functionality.
After API 21, which is Android 5.0, PowerManager introduced 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 corresponding methods to implement it.
// 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()
// System apps automatically enable proximity detection (e.g., during calls, when close to the face, the screen goes black; when far away, the screen lights up)
// But developer apps need to enable it manually
UIDevice.current.isProximityMonitoringEnabled = true
// Use notifications to listen for proximity 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, almost touching the face")
// Lock screen at close distance, which makes the screen go black and saves power
UIApplication.shared.isIdleTimerDisabled = false
} else{ // Far distance
print("Too far, can't see you")
// Do not lock screen at far distance
UIApplication.shared.isIdleTimerDisabled = true
}
}
}
Both platforms have their implementation methods, and we just need to create a Plugin to integrate it into our own project.