除了使用onLocationChanged(Location location)之外,另一种获取用户位置信息的方法是使用位置管理器和广播接收器。请参阅文档以了解有关位置管理器类的所有内容。使用位置管理器类,您将能够设置一个时间间隔,在此间隔内即使用户没有移动,也可以探测其位置。您将拥有:
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Intent intent = new Intent(context, LocationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
List<String> knownProviders = locationManager.getAllProviders();
if(locationManager != null && pendingIntent != null && knownProviders.contains(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINUTE_INTERVAL*5, 0, pendingIntent);
}
if(locationManager != null && pendingIntent != null && knownProviders.contains(LocationManager.NETWORK_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINUTE_INTERVAL*5, 0, pendingIntent);
}
在 LocationReceiver 类(Broadcast Receiver)中,您将拥有一个 onRecieve() 方法,在其中可以使用以下内容:
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
location = (Location) bundle.get(LocationManager.KEY_LOCATION_CHANGED);
您可以使用该位置对象进行许多操作,请参考Android Location文档。