我需要在SensorManager
课程中使用Fragment
,但每当我使用以下方法初始化SensorManager
时:
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
Android Studio不接受它并生成错误:
无法解决方法
如何正确地在fragment
中实现其事件监听器?
答案 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);
}
}