【问题标题】:How to get a reference to LocationManager inside a Fragment如何在 Fragment 中获取对 LocationManager 的引用
【发布时间】:2012-10-29 15:58:23
【问题描述】:

我有一个扩展 Fragment 并实现 LocationListener 的类。 当我写

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

我收到编译时错误,因为方法 getSystemService 不是 Fragment 的方法。

我可以做些什么来创建LocationManager

【问题讨论】:

    标签: android fragment locationmanager


    【解决方案1】:

    在你的片段中简单地调用这个:

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

    因此,您只需获取 Activity 并从那里调用 getSystemService()

    编辑: 由于自 API 28 起已弃用 getActivity 方法,您可以使用:

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

    【讨论】:

    • 谢谢,我很接近但无法以正确的方式得到它
    【解决方案2】:

    试试这个代码 sn-p 它会工作。

    代码:

    LocationManager locationManager = (LocationManager)
    getContext().getSystemService(Context.LOCATION_SERVICE);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多