2

我有一个 Android 应用程序,它基本上想要跟踪用户全天的动作,并每周向他们报告某些趋势。我最初认为,只要用户启用了定位服务和/或 GPS,那么系统就会一直试图让用户的位置保持最新。然而,在阅读了关于Location Strategies的文章后,我意识到事实并非如此。

看来,即使用户已选中位置服务或 GPS 框,接收器也只是在应用程序调用 requestLocationUpdates 后才真正尝试确定设备的位置,并且会继续这样做,直到调用 removeUpdates。(如果这不正确,请告诉我)。

由于我的应用程序实际上只需要对设备运动的“粗略”概念,我正在考虑每五分钟左右只记录一次设备的位置。但是,文章中的两个示例都没有描述这种应用程序。这两个示例更多地是关于确定设备在特定时间点的位置,而不是试图“跟随”设备:使用创建位置标记用户创建的内容并定位附近的兴趣点。

我的问题是,让我的应用程序每五分钟“唤醒”一次,然后使用文章中的一种技术来确定设备的当前位置(通过开始聆听、采集多个样本、确定最佳样本)是否更有效? ,停止收听,然后重新入睡),还是最好开始收听更新并在更新之间留出至少五分钟的时间,并且永远不要停止收听?

4

1 回答 1

0

即使您的应用不可见,也可以使用 BroastcastReceiver 定期获取新位置。不要使用服务,它可能会被杀死。

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(MyLocationBroadcastReceiver.action), 0);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5 * 60 * 1000, 100, pendingIntent);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5 * 60 * 1000, 100, pendingIntent);
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, pendingIntent);

不要忘记将操作字符串添加到 manifest.xml,并在那里添加 ACCESS_FINE_LOCATION 权限(用于 GPS)。如果您不需要 GPS,请使用 ACCESS_COARSE_LOCATION。

<receiver android:name="MyLocationBroadcastReceiver" android:process=":myLocationBroadcastReceiver" >
    <intent-filter>
        <action android:name="Hello.World.BroadcastReceiver.LOCATION_CHANGED" />
    </intent-filter>
</receiver>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />

在 BroastcastReceiver.onReceive() 中,您必须整理出您得到的内容。我丢弃与前一个位置的距离小于新精度的新位置。如果“最近”位置的准确性比前一个位置差很多,我也会丢弃它们。精度高于 100m 的 GPS 定位通常毫无价值。您必须将位置存储在文件或首选项中,因为您的 BroastcastReceiver 对象在 onReceive() 调用之间将不存在。

public class MyLocationBroadcastReceiver extends BroadcastReceiver
{
    static public final String action = "Hello.World.BroadcastReceiver.LOCATION_CHANGED";

    public void onReceive(Context context, Intent intent)
    {
        Location location = (Location) intent.getExtras().get(LocationManager.KEY_LOCATION_CHANGED);
        if (location == null)
        {
            return;
        }

        // your strategies here
    }
}
于 2013-08-02T09:16:58.610 回答