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