我尝试创建单独的加速度计类来保存加速度计的值,并且我可以随时从任何其他类中访问它们,但它似乎不起作用。
这是我的加速度计课程:
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
public class Accelero implements SensorEventListener {
private float xAxis;
private float yAxis;
private float zAxis;
public float getX(){
return this.xAxis;
}
public float getY(){
return this.yAxis;
}
public float getZ(){
return this.zAxis;
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent event) {
xAxis = event.values[0];
yAxis = event.values[1];
zAxis = event.values[2];
}
}
如您所见,我正在尝试通过get*();
我创建的方法获取值。但似乎总是要回来0, 0, 0
。知道我的代码有什么问题吗?
这是使用它的活动:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText output;
private static int DIS = 1;
Accelero acc;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output =(EditText) findViewById(R.id.editText1);
handler.sendEmptyMessageDelayed(DIS, 1);
acc = new Accelero(this);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == DIS){
refresh();
handler.sendEmptyMessageDelayed(DIS, 1);
}
}
};
public void refresh(){
output.setText("X:"+acc.getX()+"\nY:"+acc.getY()+"\nZ:"+acc.getZ());
}
}
我在清单中也有这个前提:
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />