Sensor_Service无法解析为变量

时间:2014-05-12 08:29:37

标签: java android

我在传感器服务上遇到错误。我非常确定这是正确的语法,除非我遗漏了一些东西。只需要加速度计的那部分。非常感谢你能发表想法。

public class AskQuestions extends Fragment {

 private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakedetector;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.fragment_questions, container, false);
       //Error
        mSensorManager = getSystemService(SENSOR_SERVICE);

        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        mShakedetector = new ShakeDetector(new OnShakeListener() {

            @Override
            public void onShake() {
                // TODO Auto-generated method stub
                handleNewAnswer();
            }
        });



        return rootView;
    }

    @Override
    public void onResume(){
        super.onResume();
        mSensorManager.registerListener(mShakedetector, mAccelerometer, 
                SensorManager.SENSOR_DELAY_UI);
    }
    @Override
    public void onPause(){
        super.onPause();
        mSensorManager.unregisterListener(mShakedetector);
    }
    private void handleNewAnswer() {
        if(makeMethink == true) {
            result = answer.makeMeThink();
        }else if(WhatsTheAnswer == true){
            result =  answer.whatsTheAnswer();
        } else if (inspireMe){
            result = answer.inspireQuotes();
        }




                displayAnswer.setText(result);
    }



}

1 个答案:

答案 0 :(得分:2)

请改用:

mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);

问题是您使用的代码仅适用于Context的子类(例如Activity)。 Fragment不是Context的子类,因此您必须获取该类型的对象才能获得系统服务。幸运的是,在Fragment中,您可以轻松地使用Activity获取容器getActivity()

SENSOR_SERVICE是Context中定义的常量,因此每当您从Context.SENSOR_SERVICE的子类外部使用它时,都必须编写Context