我正在使用以下类从Android手机中读取加速计数据:
public class AccelerometerData extends Activity implements SensorEventListener {
//variables
public AccelerometerData()
{
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO: my codes
}
}
}
现在从我的主要活动类开始,我正在调用该类来读取数据
AccelerometerData sbt = new AccelerometerData ();
它显示以下消息不幸的是,AccelerometerData已停止。我是android开发的新手,不知道这里有什么问题。
任何帮助都将受到高度赞赏。
答案 0 :(得分:2)
你正在寻找的答案可能看起来像这样。 MainActivity拥有AccelerometerData类。
public class MainActivity extends Activity {
priavte AccelerometerData ad;
private TextView someTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// "this" allows 'ad' to make calls back to the MainActivity
ad = new AccelerometerData((SensorManager)getSystemService(SENSOR_SERVICE), this);
someTextView = (TextView)findViewById(R.id.my_text_view);
}
protected void onResume() {
super.onResume();
sensorHandler.onResume();
}
protected void onPause() {
super.onPause();
sensorHandler.onPause();
}
protected void setTextViewValue(float[] values){
someTextView.setText( Float.toString(values[0]) );
}
然后在AccelerometerData类中,它可能看起来像这样。
public class AccelerometerData implements SensorEventListener {
private final SensorManager mSensorManager;
private final Sensor mAccelerometer;
private final MainActivity ma;
public AccelerometerData(SensorManager sm, MainActivity ma){
mSensorManager = sm;
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
this.ma = ma
}
protected void onResume() {
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
mSensorManager.unregisterListener(this);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
// Here we call a method in MainActivity and pass it the values from the SensorChanged event
ma.setTextViewValue( event.values );
}
}
答案 1 :(得分:0)
您的课程不应该扩展活动。它不需要。它应该由某种活动拥有。