android - android光传感器检测重大的灯光变化

  显示原文与译文双语对照的内容
110 1

我是android中的传感器新手,现在有点困惑。我只需要做一些动作,只要有明显的灯光变化,比如 就会在黑暗的房间里打开。我现在有一个非常简单的默认实现。如何告诉系统我只想对重大的光变化做出React?

 public class MainActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mLight;
private RelativeLayout mLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
 mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
 mLayout = (RelativeLayout) findViewById(R.id.mLayout);
 mLayout.setKeepScreenOn(true);
}
@Override
protected void onResume() {
 mSensorManager.registerListener(this, mLight,
 SensorManager.SENSOR_DELAY_FASTEST);
 super.onResume();
}
@Override
protected void onPause() {
 mSensorManager.unregisterListener(this);
 super.onPause();
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
 if (sensor.getType() == Sensor.TYPE_LIGHT) {
//TODO
 }
}
@Override
public void onSensorChanged(SensorEvent event) {
 if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
//TODO
 }
}
 }
时间:原作者:0个回答

79 1

尝试下面的代码:-

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class MainActivity extends Activity {
 TextView textLIGHT_available, textLIGHT_reading;
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 textLIGHT_available 
 = (TextView)findViewById(R.id.LIGHT_available);
 textLIGHT_reading 
 = (TextView)findViewById(R.id.LIGHT_reading);
 SensorManager mySensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
 Sensor LightSensor = mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
 if(LightSensor!= null){
 textLIGHT_available.setText("Sensor.TYPE_LIGHT Available");
 mySensorManager.registerListener(
 LightSensorListener, 
 LightSensor, 
 SensorManager.SENSOR_DELAY_NORMAL);
 }else{
 textLIGHT_available.setText("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){
 textLIGHT_reading.setText("LIGHT:" + event.values[0]);
 }
 }
 };
}
原作者:
...