如何显示传感器值

时间:2011-07-01 06:11:38

标签: android

如何在Android模拟器中检查是否有类似加速度计,magenetic指南针的传感器类型。 Android模拟器中是否存在默认传感器,或者我们需要将任何传感器模拟器连接到Android模拟器。

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;

import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
//import android.widget.LinearLayout;
//import android.util.Log;

import android.widget.TextView;

public class SujaproActivity extends Activity implements SensorEventListener {
SensorManager sensorManager ;
private Sensor accSensor;


private TextView outputX;
 private TextView outputY;
 private TextView outputZ;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
     accSensor = sensorManager.getSensorList(
            Sensor.TYPE_ACCELEROMETER).get(0);

     outputX = (TextView) findViewById(R.id.textView1);





    outputY = (TextView) findViewById(R.id.textView2);
    outputZ = (TextView) findViewById(R.id.textView3);
    setContentView(R.layout.main);

}
protected void onResume() {
    super.onResume();
    sensorManager.registerListener(this,accSensor,SensorManager.SENSOR_DELAY_GAME);
   // sensorManager.registerListener(this, 
      /*sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), 
      SensorManager.SENSOR_DELAY_GAME);*/
}
protected void onStop() {
    super.onStop();
    sensorManager.unregisterListener(this);
    /*sensorManager.unregisterListener(this, 
       sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION));*/
   }




public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // TODO Auto-generated method stub

}

public void onSensorChanged(SensorEvent event) {




 if (event.sensor.getType() == Sensor.TYPE_ALL)

 {        
                 outputX.setText( "x:"+Float.toString(event.values[0]));               
                 outputY.setText("y:"+Float.toString(event.values[1]));
                 outputZ.setText("z:"+Float.toString(event.values[2]));



                // default:
              /*case Sensor.TYPE_ORIENTATION:
                  outputX2.setText("x:"+Float.toString(event.values[0]));
                  outputY2.setText("y:"+Float.toString(event.values[1]));
                  outputZ2.setText("z:"+Float.toString(event.values[2]));
                  break;*/

         }

    } 
}

此代码不显示传感器值。它只显示在main.xml中绘制的设计部分。给我解决方案来显示传感器值。

1 个答案:

答案 0 :(得分:0)

我有一个工作应用程序与此代码非常相似。唯一真正的区别是我不做“if(event.sensor.getType()== Sensor.TYPE_ALL)”。我建议在onSensorChanged中放置一个日志或调试断点,看看它是否被调用。