Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a reference to LocationManager inside a Fragment

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?

like image 529
malcolm the4 Avatar asked Nov 09 '12 10:11

malcolm the4


1 Answers

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);
like image 60
Rafael T Avatar answered Oct 11 '22 12:10

Rafael T