I want TextViews to display the sensors readings in a Fragment. When trying to initialize the SensorManager the getSystemService
sensorManager = (SensorManager)
requireActivity().getSystemService(Context.SENSOR_SERVICE);
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)
For kotlin this is what worked for me.
private fun hideKeyboard() {
val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (inputManager.isAcceptingText) {
inputManager.hideSoftInputFromWindow(activity?.currentFocus?.windowToken, 0)
}
}
On Kotlin use:
this.sensorManager = activity!!.getSystemService(Context.SENSOR_SERVICE) as SensorManager
sensorManager = (SensorManager) getActivity().getSystemService(Context.NAMEOF_SERVICE);
Fragments cannot directly call System Services , You have to use Activity with which these Fragment is Attached