oboard

oboard

https://oboard.eu.org/
github
email
tg_channel
medium
twitter
bilibili
steam_profiles
follow

Flutter 實現貼耳熄屏

離臉近屏幕就黑了,離得屏幕主亮了
打電話的時候有了它就能避免誤觸
找不到
可是搜遍了整個 flutter 組織都沒有發現相關代碼
於是我打算自己動手豐衣足食⬇️

Android#

在 Android 中 API21 之前是需要自己手動寫距離傳感器和熄屏亮屏的
而到 API21 也就是 Android 5.0 之後,PowerManager 加入了新的常量

PROXIMITY_SCREEN_OFF_WAKE_LOCK

使得這個功能實現起來非常簡單

if ((pm.getSupportedWakeLockFlags()  
 & PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) != 0x0) {  
    mProximityWakeLock = pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, LOG_TAG);  
}  

iOS#

在 iOS 中,也有相應的方法實現

// 近距離傳感器的實現封裝在UIKit中  

// 需要使用真機測試  

import UIKit  

class ViewController: UIViewController {  
     
    override func viewDidLoad() {  
        super.viewDidLoad()  
        
        // 系統APP自動開啟了近距離檢測(如:打電話,離臉近屏幕就黑了,離的遠屏幕主亮了)  
        // 但開發者APP需要手動開啟  
        UIDevice.current.isProximityMonitoringEnabled = true  
        
        // 使用通知監聽距離變化  
        NotificationCenter.default.addObserver(self, selector: #selector(proximityStateChanged), name: NSNotification.Name.UIDeviceProximityStateDidChange, object: nil)  
    }  
     
    @objc private func proximityStateChanged(){  
        if UIDevice.current.proximityState == true{ // 近距離  
            print("太近了,都貼臉上了")  
            // 近距離鎖屏,就是讓屏幕變黑,省電  
            UIApplication.shared.isIdleTimerDisabled = false  
        } else{ // 遠距離  
            print("太遠了,都看不見你了")  
            // 遠距離不鎖屏  
            UIApplication.shared.isIdleTimerDisabled = true  
        }  
    }  
}  

兩個平台的實現方法都有了,我們只需要做成 Plugin 就可以集成到自己的項目當中了

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。