Android 如何在活动中接收广播位置?
我已经构建了一个IntentService来在后台收集位置数据(根据用户的知识)。它使用PendingEvent来接收位置,而不是LocationListener。我在接收器中接收到位置 但是如何从活动中提取这些位置?我可以直接接收位置广播,还是需要发送新类型的广播以接收活动 服务:Android 如何在活动中接收广播位置?,android,Android,我已经构建了一个IntentService来在后台收集位置数据(根据用户的知识)。它使用PendingEvent来接收位置,而不是LocationListener。我在接收器中接收到位置 但是如何从活动中提取这些位置?我可以直接接收位置广播,还是需要发送新类型的广播以接收活动 服务: Intent activeIntent = new Intent(this, LocationReceiver.class); PendingIntent pendingIntent = Pendi
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
}
我会使用相同的广播事件 为您的意图定义更通用的操作
Intent activeIntent = new Intent("com.mypackage.myproduct.ACTION_LOCATION_CHANGED");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, activeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
...
然后,在清单中注册LocationReceiver
,并将该操作作为筛选器。这样,您将始终在LocationReceiver
中接收广播
最后,要在活动中获得广播,请在onResume/onPause中注册/取消注册匿名广播接收器(同样,将您的操作作为筛选器)。我将使用相同的广播事件 为您的意图定义更通用的操作
Intent activeIntent = new Intent("com.mypackage.myproduct.ACTION_LOCATION_CHANGED");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, activeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
...
然后,在清单中注册LocationReceiver
,并将该操作作为筛选器。这样,您将始终在LocationReceiver
中接收广播
最后,要在活动中获得广播,请注册/取消注册匿名广播接收器(同样,将您的操作作为筛选器)在onResume/onPause中。可以使用公共类的公共变量进行更新和访问。活动如何知道何时读取这些变量?这不是一种有效的方法,只需异步检查该活动中的值是否更改即可。您可以定义一个静态类来接收代码内部的更新。或者尝试共享引用来保存它们。这些建议是不可接受的解决方案。您可以使用公共类的公共变量进行更新和访问。活动如何知道何时读取它们?这不是一种有效的方法,但可以通过异步检查该类中的值是否更改来实现活动..您可以定义一个静态类来接收代码内部的更新。这些建议是不可接受的解决方案,如果你知道怎么做的话,那就太好了。谢谢。聪明,只要你知道怎么做就容易了。谢谢