Android - 一段时间后获取位置

Android - get location after some time

我可以使用 LocationManager 获取 minDistance 和 minTime 的位置。

但是,例如,我如何才能每 15 秒获取一次位置? (即使用户没有移动)

        if (Utils.hasProvider(LocationManager.GPS_PROVIDER)) {
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 15000, 100f, this);
        }

        if (Utils.hasProvider(LocationManager.NETWORK_PROVIDER)) {
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 15000, 100f, this);
        }

使用 AlarmManager 执行 this.See 这个 answer。将时间替换为 5 分钟。

否则,您可以使用

         Runnable runnable = new Runnable() {

         public void run() 
                {
                    //Your code to fetch location
                }
            };

            Handler handler1 = new Handler();
            handler1.postDelayed(runnable, 15000);

这里15000是15秒

Google 文档说

The minDistance parameter can also be used to control the frequency of location updates. If it is greater than 0 then the location provider will only send your application an update when the location has changed by at least minDistance meters, AND at least minTime milliseconds have passed. However it is more difficult for location providers to save power using the minDistance parameter, so minTime should be the primary tool to conserving battery life.

因此涉及到一个AND条件。所以你应该将距离参数设置为 0。在这种情况下,你将每 15 秒更新一次位置。

您可以使用 IntentService 并在 onstartcommand 调用 runnable 到 post 您的位置,就像这样

   Handler handler.postDelayed(postGpsRunnable, 15000);