即使您的应用程序不可见,也可以定期使用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
}
}