如何在按钮的onClick方法中注册传感器监听器?

时间:2013-04-10 13:48:26

标签: android button override listener accelerometer

我有一个应用程序,我想在点击按钮时启动加速度计的监听器,所以我尝试了这样:

private SensorManager sensorManager;

@Override
public void onCreate (Bundle savedInstanceState){

    super.onCreate(savedInstanceState);
    setContentView(R.layout.storing_act);

    Button start = (Button)findViewById(R.id.startl);

    start.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
            sensorManager.registerListener(this, 
                    sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                    SensorManager.SENSOR_DELAY_NORMAL);
        }
    });

但是它显示为

的消息
  

" SensorManager类型中的方法registerListener(SensorEventListener,Sensor,int)不适用于参数(new View.OnClickListener(){},Sensor,int)"

有没有办法轻松解决?我是否必须覆盖任何其他方法?感谢

1 个答案:

答案 0 :(得分:2)

您需要使用MyActivity.this,因为this引用OnClickListenerregisterListener方法需要SensorEventListener

public class MyActivity extends Activity implements SensorEventListener {
    @Override
    public void onCreate (Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        setContentView(R.layout.storing_act);

        Button start = (Button)findViewById(R.id.startl);

        start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
                sensorManager.registerListener(MyActivity.this, 
                        sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                        SensorManager.SENSOR_DELAY_NORMAL);
            }
        });
}