我制作了这个代码,我在教程中找到并进行了一些更改。该代码显示了方向和加速计传感器,当智能手机改变45°时,它会计算曲线的数量。它完美地运作。但我看到SENSOR_ORIENTATION,SENSOR_ACCELEROMETER已被弃用。如何使用非弃用的常量更改我的代码并使其保持工作?我是android编程和堆栈溢出的初学者。谢谢!
public class MainActivity extends Activity implements SensorListener {
private long lastUpdate=0;
private float last_x = 0;
final String tag = "IBMEyes";
SensorManager sm = null;
TextView xViewA = null;
TextView yViewA = null;
TextView zViewA = null;
TextView xViewO = null;
TextView yViewO = null;
TextView zViewO = null;
TextView mud=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.activity_main);
xViewA = (TextView) findViewById(R.id.xbox);
yViewA = (TextView) findViewById(R.id.ybox);
zViewA = (TextView) findViewById(R.id.zbox);
xViewO = (TextView) findViewById(R.id.xboxo);
yViewO = (TextView) findViewById(R.id.yboxo);
zViewO = (TextView) findViewById(R.id.zboxo);
mud=(TextView) findViewById(R.id.mud);
}
static int cont =0;
//se (valor_INICIAL - VALOR_ATUAL) > 45
@SuppressWarnings("deprecation")
public void onSensorChanged(int sensor, float[] values) {
synchronized (this) {
Log.d(tag, "onSensorChanged: " + sensor + ", x: " +
values[0] + ", y: " + values[1] + ", z: " + values[2]);
if (sensor == SensorManager.SENSOR_ORIENTATION) {
xViewO.setText("Orientation X: " + values[0]);
yViewO.setText("Orientation Y: " + values[1]);
zViewO.setText("Orientation Z: " + values[2]);
double diffDegree = Math.abs(values[0] - last_x);
if (diffDegree > 45)
{
last_x = values[0];
mud.setText("cont: "+ ++cont);
}
}
}
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
xViewA.setText("Accel X: " + values[0]);
yViewA.setText("Accel Y: " + values[1]);
zViewA.setText("Accel Z: " + values[2]);
}
}
private void setText(string mud) {
// TODO Auto-generated method stub
}
protected void onResume() {
super.onResume();
// register this class as a listener for the orientation and accelerometer sensors
sm.registerListener(this,
SensorManager.SENSOR_ORIENTATION |SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onStop() {
// unregister listener
sm.unregisterListener(this);
super.onStop();
}
@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
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item); }
@Override
public void onAccuracyChanged(int sensor, int accuracy) {
Log.d(tag,"onAccuracyChanged: " + sensor + ", accuracy: " + accuracy);
}
}
答案 0 :(得分:0)
每当您想要引用传感器时,请使用:Sensor.TYPE_XXXX。例如:Sensor.TYPE_ACCELEROMETER& Sensor.TYPE_ORIENTATION。
我不知道是否需要它,但你可能想检查是否" sm" onResume()中为null。 此外,您可能希望在onPause()而不是onStop()中取消注册SensorEventListener。