getSystemServices is undefined when called in a Fragment?

微笑、不失礼 提交于 2019-11-30 03:07:40

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.

Use:

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

Fragments cannot directly call System Services , You have to use Activity with which these Fragment is Attached

On Kotlin use:

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

You can also get the context from the LayoutInflater.

SensorManager sm = (SensorManager) getLayoutInflater().getContext().getSystemService(Context.SENSOR_SERVICE);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!