【问题标题】:Unsubscribe LocationListener from LocationManager after getting location data获取位置数据后从 LocationManager 取消订阅 LocationListener
【发布时间】:2011-12-11 18:06:55
【问题描述】:

由于某种原因,当我在 requestLocationUpdates() 方法之后添加 removeUpdates() 时,我根本没有获得任何位置数据。我没有正确退订吗?

LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 5000, 1, mlocListener);
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 1, mlocListener);
mlocManager.removeUpdates(mlocListener);


public class MyLocationListener implements LocationListener
    {
        @Override
        public void onLocationChanged(Location loc)
        {
            loc.getLatitude();
            loc.getLongitude();
            String text = "My current location is: " +
            "Latitude = " + loc.getLatitude() +
            "Longitude = " + loc.getLongitude();
            System.out.println("FINISHED:");
            Toast.makeText( getApplicationContext(),
                    text,
                    Toast.LENGTH_SHORT).show();

        }
}

【问题讨论】:

    标签: android gps locationmanager locationlistener


    【解决方案1】:

    您可以尝试创建一种方法并在其中执行 removeUpdates() 。获取数据后从 onLocationChanged() 调用它。

    【讨论】:

    • 你的意思是把额外的方法放在myLocationListener或者调用myLocationListener的类里?
    • 我的意思是在你的活动或课堂上。制作一种方法并放入 mlocManager.removeUpdates(mlocListener);在方法的主体中。现在,在获取您的位置和数据后,只需从那里调用该方法并完成:)。
    【解决方案2】:

    This 可能会有所帮助。

    您在获得位置数据后取消订阅,这意味着在onLocationChanged 方法中。

    【讨论】:

    • 我明白你的意思,但是我无法访问onLocationChanged() 方法中的removeUpdates() 方法
    • mlocManager 声明为final,然后您就可以在removeUpdates 中访问它。
    • 我的意思是它是在不同的类中声明的,公开它是不好的做法。
    • 所以想办法在onLocationChanged方法中获取对上下文的引用。这就是做你需要的方式......
    【解决方案3】:

    我最终在我的LocationHandler 中创建了一个Thread,其中嵌套了一个while,它一直循环直到找到 GPS 位置。当发现我取消订阅我的LocationListener

    【讨论】:

    • 我见过的最脏的东西之一 :(
    猜你喜欢
    • 1970-01-01
    • 2018-10-17
    • 2016-07-27
    • 2018-12-15
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    相关资源
    最近更新 更多