注册SensorManager.registerListener时,我的Android应用程序崩溃了

时间:2014-12-03 03:29:31

标签: sensormanager

以下是我的代码。当我调用SensorManager.registerListener时遇到问题,我的应用程序将崩溃。有人能告诉我发生了什么事吗? 我只需按照Web指南设置SensorManger,传感器(加速度计),然后注册动作lintener以检测加速度计的情况。 我使用API​​ 21来开发这个应用程序。

public class MainActivity extends ActionBarActivity implements SensorEventListener{
private TextView tip;
private SensorManager mSensorManager;
private Sensor mSensor;
private float axisX = 0;             
private float axisY = 0 ;  
private float axisZ = 0;

@Override  
protected void onResume() {    
    super.onResume();    
    setUpAcceleratorSensor();
    mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL); 
}

@Override
protected void onPause() { 
    super.onPause();  
    mSensorManager.unregisterListener(this);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setUpAcceleratorSensor();
}

@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) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private void setUpAcceleratorSensor(){
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    if((mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)) != null);
    else
        Toast.makeText(this, "No Sensor Device Exist", Toast.LENGTH_LONG).show();
 }

@Override
public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub
    Sensor mySensor = event.sensor;

    if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        if(event.values[0] != 0 || event.values[1] != 0 || event.values[2] != 0){
            axisX = event.values[0];             
            axisY = event.values[1];              
            axisZ = event.values[2];    
            tip.setText("Detect your montion");
        }
    }
    else
        Toast.makeText(this, "Cannot Get Sensor Device", Toast.LENGTH_LONG).show();
}

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

}
}

感谢。

2 个答案:

答案 0 :(得分:0)

首先,我总是检查这样的事情是否出错,是检查您是否拥有Android Manifest中的所有正确权限;但是,我不认为有任何与使用位置传感器相关的权限。我会先检查一下。首先想到的是,在发布logcat之后,我们将能够提供更详细的答案。

答案 1 :(得分:0)

尝试以这种方式获取传感器

mSensor = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);代替您的setUpAccelerometer()方法。