Java 如何使用传感器结果创建单独的类
我对简单的代码有问题:在mainActivity中,我需要检查手机上是否有传感器(例如光传感器),如果有,我需要在屏幕上显示此传感器的结果,但负责从传感器读取数据的代码必须在单独的类中。我写了简单的代码,但它不起作用。当我运行此代码时,我的手机只会显示:“亮度:0.0”。我是编程新手,请帮帮我 主要类别: 公共类MainActivity扩展了活动{Java 如何使用传感器结果创建单独的类,java,android,sensors,android-sensors,Java,Android,Sensors,Android Sensors,我对简单的代码有问题:在mainActivity中,我需要检查手机上是否有传感器(例如光传感器),如果有,我需要在屏幕上显示此传感器的结果,但负责从传感器读取数据的代码必须在单独的类中。我写了简单的代码,但它不起作用。当我运行此代码时,我的手机只会显示:“亮度:0.0”。我是编程新手,请帮帮我 主要类别: 公共类MainActivity扩展了活动{ LightSensor mLightSensor = null; protected SensorManager mSensorManager;
LightSensor mLightSensor = null;
protected SensorManager mSensorManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView wyswietl = (TextView)findViewById(R.id.res);
mLightSensor = new LightSensor();
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT) != null){
LightSensor lS = new LightSensor();
wyswietl.setText("Light level: " + Float.toString(lS.lux));
}
else{
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onResume(){
super.onResume();
mLightSensor.register();
}
@Override
protected void onPause(){
super.onPause();
mLightSensor.unregister();
}
}
和光传感器等级:
公共类LightSensor实现SensorEventListener{
SensorManager mSensorManager;
Sensor lightManager;
public float lux;
public Context context;
public void onCreateLight(Context context){
this.context = context;
mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
lightManager = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
lux = event.values[0];
}
public void register(){
mSensorManager.registerListener(this, lightManager, SensorManager.SENSOR_DELAY_NORMAL);
}
public void unregister(){
mSensorManager.unregisterListener(this);
}
}
我还没有测试它,但是您可以在LightSensor类中创建一个新方法,将lux变量返回到主类 比如:
public float getLux(){
return lux;
}
然后在你的“MainActivity”课程中,你可以调用
float newLux = mLightSensor.getLux();
如果它不起作用,我可能会有一个稍微复杂一点的解决方案。您永远不会调用mLightSensor.onCreateLight() 将onCreateLight更改为LightSensor类的构造函数怎么样。这将解决问题,并且不需要您记住调用CreateLight
public LightSensor(Context context){
this.context = context;
mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
lightManager = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
}
即使它起作用。。目前,我总是在运行窗口“传感器应用程序已停止”后运行它。您是否检查了您的光传感器是否正常工作?您可以使用日志检查是否从lux获得了一些实际值:您能帮助我并写下我如何做到这一点吗?但我应该写什么作为此构造函数的参数?我已经编辑了我的注释,以显示LightSensor构造函数的示例。