Using proximity sensor in android

后端 未结 4 2149
慢半拍i
慢半拍i 2020-12-01 03:44

I want to use proximity sensor in my project. I searched for proximity sensor tutorial. And I found a sensor tutorial at http://www.vogella.com/articles/AndroidSensor/articl

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 04:45

    The right way to use proximity sensor is via PowerManager. Forget about light sensor and use Android abstraction and already written code!

    public class ProximityViaPowerManager {
    
    private Context context;
    private WakeLock proximityWakeLock;
    
    public ProximityViaPowerManager(Context context) {
        this.context = context;
    }
    
    public boolean enableProximityWakeLock() {
        if (proximityWakeLock != null) {
          return true;
        }
        PowerManager powerManager = 
     context.getApplicationContext().getSystemService(Context.POWER_SERVICE);
        proximityWakeLock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
        proximityWakeLock.acquire();
        return true;
      }
    
      public void disableProximityWakeLock() {
        if (proximityWakeLock != null) {
          proximityWakeLock.release();
          proximityWakeLock = null;
        }
      }
    }
    

    Ensure correct enable/disable capability in Android life cycle resume/pause and add the permission to manifest:

    
    

提交回复
热议问题