[英]Android: How to detect if the light sensor of android is covered by hand
I am a new Android developer and working on a fun project. 我是一名新的Android开发人员,正在从事一个有趣的项目。 I want to make the cell phone beeps for couple of seconds if the light sensor is covered. 如果覆盖了光传感器,我想让手机发出几声哔声。 But I don't know what event is triggered when the light sensor is covered. 但是我不知道覆盖光传感器会触发什么事件。 Can some one give me a hint please what that event would be ? 有人可以给我提示一下那件事是什么吗?
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SensorManager sensorManager = (SensorManager) this.getSystemService(this.SENSOR_SERVICE);
Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
( some event ???) {
// if some one coveres the light sensor then beep sound is played
ToneGenerator toneGen1 = new ToneGenerator(AudioManager.STREAM_MUSIC, 200);
toneGen1.startTone(ToneGenerator.TONE_CDMA_ABBR_REORDER,15000);
}
if (lightSensor != null){
Toast.makeText(this, "There is a sensor light ",
Toast.LENGTH_SHORT).show();
}
else {
// Failure! sensor not available.
Toast.makeText(this, "No sensor light",
Toast.LENGTH_SHORT).show();
}
}
} }
use below code
SensorManager mySensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
Sensor LightSensor = mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
float max = lightSensor.getMaximumRange();
if(LightSensor != null){
textLIGHT_available.setText("Sensor.TYPE_LIGHT Available");
mySensorManager.registerListener(
LightSensorListener,
LightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}else{
//Sensor.TYPE_LIGHT NOT Available;
}
}
private final SensorEventListener LightSensorListener
= new SensorEventListener(){
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_LIGHT){
Toast.makeText(Activity.this,"LIGHT: " + event.values[0],Toast.LENGTH_SHORT).show();
if(event.values[0]/max<treashold)
{
//do here treasholde value is between 0 and 1
}
}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.