Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

android - getSystemServices is undefined when called in a Fragment?

I want TextViews to display the sensors readings in a Fragment. When trying to initialize the SensorManager the getSystemServices is undefined in the Fragment, eclipse says.Why and how to fix it.

Fragment

public class FragSensors extends Fragment {

private TextView accXTv, accYTv, accZTv;
private SensorManager sensorManager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View v = inflater.inflate(R.layout.frag_sensors, container, false);
    accXTv = (TextView) v.findViewById(R.id.accXValue);
    accYTv = (TextView) v.findViewById(R.id.accYValue);
    accZTv = (TextView) v.findViewById(R.id.accZValue);
    return v;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

}

private final SensorEventListener mSensorListener = new SensorEventListener() {

    @Override
    public void onSensorChanged(SensorEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
        // TODO Auto-generated method stub

    }
};

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just one more method call:

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

Why that one extra method call?
the getSystemService() method that provides access to system services comes from Context. An Activity extends Context, a Fragment does not. Hence, you first need to get a reference to the Activity in which the Fragment is contained and then magically retrieve the system service you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...