【发布时间】:2011-10-10 17:11:03
【问题描述】:
我已经构建了一个 IntentService 来在后台收集位置数据(在用户知情的情况下)。它使用 PendingIntent 来接收位置,而不是 LocationListener。我在接收器中接收位置很好。
但是如何从 Activity 中获取这些位置?我可以直接接收位置广播,还是需要发送新类型的广播才能接收活动?
服务:
Intent activeIntent = new Intent(this, LocationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, activeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
LocationManager locationManager = (LocationManager) (App.getInstance().getSystemService(Context.LOCATION_SERVICE));
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_TIME_CHANGE, LOCATION_DISTANCE_CHANGE, pendingIntent);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_TIME_CHANGE, LOCATION_DISTANCE_CHANGE, pendingIntent);
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, LOCATION_TIME_CHANGE, LOCATION_DISTANCE_CHANGE, pendingIntent);
接收者:
@Override
public void onReceive(Context context, Intent intent) {
Bundle b = intent.getExtras();
Location loc = (Location)b.get(android.location.LocationManager.KEY_LOCATION_CHANGED);
// TODO handle the location here
}
【问题讨论】:
-
您可以使用公共类的公共变量在别处进行更新和访问
-
那么活动如何知道何时阅读它们?
-
这不是一种有效的方法,但可以通过异步检查该活动中的值是否发生变化来实现..
-
您可以定义一个静态类来接收代码中的更新。或者尝试使用 SharedPreferences 来保存它们。
-
这些建议不是可接受的解决方案
标签: android