我想使用多個類來顯示加速度計讀數。我試圖在單個類中獲得加速度計讀數,並且運行得非常好。 但是在這個代碼的輸出是0.00000,0.000000,0.00000Android加速度計讀數
這裏是我的兩個類:
package com.example.sample;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
import android.content.Context;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AccData accl=new AccData();
accl.mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accl.sensor = accl.mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
accl.register();
String result=accl.getAccelerometerReading();
TextView display=(TextView)findViewById(R.id.tv);
display.setText(result);
}
}
2.
package com.example.sample;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.app.Activity;
import android.content.Context;
public class AccData extends Activity implements SensorEventListener {
public float acclX,acclY,acclZ;
public SensorManager mSensorManager;
public Sensor sensor;
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
acclX = event.values[0];
acclY =event.values[1];
acclZ = event.values[2];
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
public void register() {
// TODO Auto-generated method stub
mSensorManager.registerListener(this, sensor,SensorManager.SENSOR_DELAY_NORMAL);
}
protected void unregister() {
mSensorManager.unregisterListener(this, sensor);
}
protected String getAccelerometerReading()
{
return String.format("%7f" + ", %7f"+ ", %7f" ,acclX,acclY,acclZ);
}
}
如何更新顯示的TextView的內容?當第一個活動創建時,您只設置**一次**。 –
是的。你是對的。但是,如何更新textview的內容? – khand041
而且還通過調試,我意識到,程序控制不進入onSensorChanged函數 – khand041