2017-03-08 42 views
0

我需要在Fragment類使用SensorManager,但每當我初始化SensorManager用以下方法:如何在片段類中使用傳感器事件方法?

mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); 

的Android Studio不接受它,並生成一個錯誤:

Cannot resolve method

哪有我在fragment中正確實現了它的事件監聽器?

+0

'getActivity()。getSystemService..' –

+0

感謝您的回覆其工作,但我想實現傳感器事件偵聽片段是有任何的例子嗎? –

+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); 
} 

}

相關問題