如何在片段类中使用传感器事件方法?

时间:2017-03-08 17:07:34

标签: java android android-studio android-fragments

我需要在SensorManager课程中使用Fragment,但每当我使用以下方法初始化SensorManager时:

mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); 

Android Studio不接受它并生成错误:

  

无法解决方法

如何正确地在fragment中实现其事件监听器?

1 个答案:

答案 0 :(得分:0)

public class MyFragment extends Fragment implements SensorEventListener {
private SensorManager mSensorManager;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSensorManager = (SensorManager)        

this.getActivity().getSystemService(Activity.SENSOR_SERVICE);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,  
Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.mylayout, container, false);

    return rootView;
}

@Override
public void onSensorChanged(SensorEvent event) {
    float x = event.values[0], y = event.values[1];
}

@Override public void onAccuracyChanged(Sensor sensor, int accuracy) { }

@Override
public void setMenuVisibility(boolean menuVisible) {
    super.setMenuVisibility(menuVisible);

    // First starts (gets called before everything else)
    if(mSensorManager == null) {
        return;
    }

    if(menuVisible) {
        this.registerSensorListener();
    } else {
        this.unregisterSensorListener();
    }   
}

@Override
public void onStart() {
    super.onStart();

    if(this.getUserVisibleHint()) {
        this.registerSensorListener();
    }
}

@Override
public void onStop() {
    super.onStop();
    this.unregisterSensorListener();
}

private void registerSensorListener() {
    mSensorManager.registerListener(this, 
mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0), 
SensorManager.SENSOR_DELAY_FASTEST);
}

private void unregisterSensorListener() {
    mSensorManager.unregisterListener(this);
}

}