16

I have a class that extends Fragment and implements LocationListener. When I write

LocationManager myLocalManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);

I get an compile time error because the method getSystemService is not a method of Fragment.

What can I do in order to create the LocationManager?

Rafael T
  • 14,504
  • 14
  • 72
  • 137
malcolm the4
  • 307
  • 2
  • 5
  • 15

2 Answers2

65

inside your fragment simply call this:

LocationManager mgr = 
(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);

So you simply get the Activity and call getSystemService() from there

Edit: As the getActivity method is deprecated since API 28 you can just use:

LocationManager mgr = 
    (LocationManager)getContext().getSystemService(Context.LOCATION_SERVICE);
Rafael T
  • 14,504
  • 14
  • 72
  • 137
0

Try this code snippet it will work.

Code :

LocationManager locationManager = (LocationManager)
getContext().getSystemService(Context.LOCATION_SERVICE);
RajeeshMenoth
  • 999
  • 2
  • 12
  • 27
ankit682
  • 19
  • 6