在片段中调用时,getSystemServices是否未定义?

时间:2014-06-26 09:53:12

标签: android android-fragments android-sensors

我希望TextViewsFragment中显示传感器读数。当试图初始化SensorManager时,getSystemServices中的Fragment未定义,eclipse说。为什么以及如何修复它。

片段

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

    }
};

}

8 个答案:

答案 0 :(得分:119)

再多一个方法调用:

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

为什么要拨打一个额外的方法?
提供对系统服务的访问权限的getSystemService()方法来自ContextActivity延伸ContextFragment则不延伸Activity。因此,您首先需要获取包含Fragment的{​​{1}}的引用,然后神奇地检索所需的系统服务。

答案 1 :(得分:22)

使用:

getActivity().getSystemService(name)

答案 2 :(得分:3)

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

片段无法直接调用系统服务,您必须使用附加了这些片段的活动

答案 3 :(得分:2)

在Kotlin上使用:

this.sensorManager = activity!!.getSystemService(Context.SENSOR_SERVICE) as SensorManager

答案 4 :(得分:1)

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

答案 5 :(得分:0)

您还可以从LayoutInflater获取上下文。

SensorManager sm = (SensorManager) getLayoutInflater().getContext().getSystemService(Context.SENSOR_SERVICE);

答案 6 :(得分:0)

对于Kotlin来说,这对我有用。

private fun hideKeyboard() {
        val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (inputManager.isAcceptingText) {
            inputManager.hideSoftInputFromWindow(activity?.currentFocus?.windowToken, 0)
        }
    }

答案 7 :(得分:0)

就我而言,这有帮助:

val manager = context!!.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager