2013-04-20 145 views
2

我有一个Android应用程序,基本上想跟踪用户的整个一天的运动,并每周向他们报告一些趋势。我最初认为,只要用户具有位置服务和/或GPS功能,系统总是试图保持用户的位置是最新的。但是,在阅读Location Strategies的文章后,我意识到情况并非如此。以短间隔或长时间间隔长间隔请求位置更新是否更好?

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

由于我的应用程序真的只需要设备运动的“粗略”概念,因此我一直在考虑每五分钟左右记录一次设备的位置。但是,这篇文章中的例子都没有描述这种应用。这两个例子都是关于确定设备在特定时间点的位置,而不是试图“跟随”设备:标记用户创建的内容与其创建的位置并找到附近的兴趣点。

我的问题是,让我的应用程序每五分钟“唤醒”一次,然后使用文章中的技术之一确定设备的当前位置会更有效率(通过开始聆听,确定最佳样本,停止收听,然后回到睡眠状态),还是最好开始收听更新,并在五分钟更新之间给出最短时间并且永不停止收听?

回答

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()中,您必须理清所得到的结果。我扔掉新位置的距离比以前的位置少,而不是新的准确度。如果他们的准确度比前一个更差,我也会扔掉“最近”的位置。精度高于100米的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 
    } 
}