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