【问题标题】:Wait for current location - GPS - Android Dev等待当前位置 - GPS - Android Dev
【发布时间】:2012-05-10 16:28:17
【问题描述】:

我必须等待才能获得当前位置,就像您在 Google 地图中并请求您的位置时一样。如果它无法获得任何位置,则通知错误并且什么也不做。

我在这里和网上阅读了答案,但都说我必须使用getLastKnownLocation 方法,但我不需要这个,我只需要当前位置。如果没有,我什么都不做。

【问题讨论】:

    标签: android gps


    【解决方案1】:

    从昨天开始阅读:GPS Android - get positioning only once

    但是,您可以通过以下方式获取当前位置:

    public class Example extends Activity implements LocationListener {
        LocationManager mLocationManager;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    
            Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if(location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
                // Do something with the recent location fix 
                //  if it is less than two minutes old,
                //  otherwise wait for the update below
            }
        }
    
        public void onLocationChanged(Location location) {
            if (location != null) {
                Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
                // You need to call this whenever you are done:
                // mLocationManager.removeUpdates(this);
            }
        }
    
        // Required functions    
        public void onProviderDisabled(String arg0) {}
        public void onProviderEnabled(String arg0) {}
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
    }
    

    【讨论】:

    • 谢谢!我会试试这个。一个问题,我的方法如何等待位置更新才能做一些事情。例如将位置保存在数据库中。我应该使用等待,通知吗??
    • 我不明白你的问题......当每个新的 GPS 位置在 onLocationChanged() 中提供给你时,你可以对它做一些事情。如果您只想每 5 分钟或 500 米检查一次新位置,请更改 requestLocationUpdates()。
    • Sam,例如,如果我想将获得的位置存储在数据库中,我必须等到 GPS 获得位置,这就是我的意思。
    • 好的,onLocationChanged() 仅在新位置可用时调用,并且在那里您可以调用db.insert(location.getTime(), location.getLatitude(), location.getLongitude()); 之类的方法将位置保存到数据库中。数据库方面的帮助start here
    • 山姆是对的;启动您的应用程序,启用 GPS,然后返回。当(如果)位置最终可用时,将调用您的 onLocationChanged() 方法。然后,一旦获得位置,您就可以做任何您想做的事情,禁用 GPS,您就完成了。另外:我会设置一个处理程序并使用 postDelayed() 超时十分钟左右。如果处理程序在您获得位置之前被调用,那么是时候放弃了,因为您不会获得位置。
    猜你喜欢
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    相关资源
    最近更新 更多