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);
}
}
'getActivity()。getSystemService..' –
感謝您的回覆其工作,但我想實現傳感器事件偵聽片段是有任何的例子嗎? –
會有很多,只需要谷歌它與你需要什麼 –