我正在开发一个带有光传感器的项目,但我的问题是光传感器总是返回 null 而我的测试设备是samsung galaxy y。我的疑问:是我的光传感器代码错误还是我的银河 y 不包含光传感器?
我试过下面的代码:
package com.example.lightsensor;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class LightSensorActivity extends Activity {
ProgressBar lightMeter;
TextView textMax, textReading;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.light_sensor_layout);
lightMeter = (ProgressBar)findViewById(R.id.lightmeter);
textMax = (TextView)findViewById(R.id.max);
textReading = (TextView)findViewById(R.id.reading);
SensorManager sensorManager
= (SensorManager)getSystemService(Context.SENSOR_SERVICE);
Sensor lightSensor
= sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if (lightSensor == null){
Toast.makeText(LightSensorActivity.this,
"No Light Sensor! quit-",
Toast.LENGTH_LONG).show();
}else{
float max = lightSensor.getMaximumRange();
lightMeter.setMax((int)max);
textMax.setText("Max Reading: " + String.valueOf(max));
sensorManager.registerListener(lightSensorEventListener,
lightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
SensorEventListener lightSensorEventListener
= new SensorEventListener(){
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if(event.sensor.getType()==Sensor.TYPE_LIGHT){
float currentReading = event.values[0];
lightMeter.setProgress((int)currentReading);
textReading.setText("Current Reading: " + String.valueOf(currentReading));
}
}
};
}
任何人都可以帮助我代码有什么问题或设备不包含光传感器吗?
提前致谢!