Android:当使用LocationManager.requestLocationUpdates()时,如何从intent bundle extras获取位置信息
我正在尝试使用Android的LocationManager RequestLocationUpdate。在我尝试提取广播接收器中的实际位置对象之前,一切都正常。我是否需要为我的自定义意图专门定义“额外内容”,以便在我将其传递给RequestLocationUpdate之前,Android LocationManager知道如何将其添加到意图中,或者无论何时将激发的意图传递给广播接收器,它都会创建额外内容包 我的代码如下所示:Android:当使用LocationManager.requestLocationUpdates()时,如何从intent bundle extras获取位置信息,android,geolocation,intentfilter,android-intent,Android,Geolocation,Intentfilter,Android Intent,我正在尝试使用Android的LocationManager RequestLocationUpdate。在我尝试提取广播接收器中的实际位置对象之前,一切都正常。我是否需要为我的自定义意图专门定义“额外内容”,以便在我将其传递给RequestLocationUpdate之前,Android LocationManager知道如何将其添加到意图中,或者无论何时将激发的意图传递给广播接收器,它都会创建额外内容包 我的代码如下所示: Intent intent = new Intent("com.my
Intent intent = new Intent("com.myapp.swarm.LOCATION_READY");
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
0, intent, 0);
//Register for broadcast intents
int minTime = 5000;
int minDistance = 0;
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime,
minDistance, pendingIntent);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
我有一个广播接收器,在宣言中定义为:
<receiver android:name=".LocationReceiver">
<intent-filter>
<action android:name="com.myapp.swarm.LOCATION_READY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
我的“loc”对象为空。好的,我通过将广播接收器代码中更改的密钥位置更改为:
public class LocationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//Do this when the system sends the intent
Bundle b = intent.getExtras();
Location loc = (Location)b.get(android.location.LocationManager.KEY_LOCATION_CHANGED);
Toast.makeText(context, loc.toString(), Toast.LENGTH_SHORT).show();
}
}
我已经尝试编写和测试您提出的解决方案,因为我面临着类似的问题,涉及到邻近警报和携带位置对象的意图。根据您提供的信息,您成功地克服了BroadcastReceiver端的空对象检索。您可能没有注意到的是,现在您应该接收到与最初创建的意图相同的位置(也被视为:意图缓存问题) 为了克服这个问题,我使用了FLAG_CANCEL_CURRENT,正如这里很多人所建议的那样,它工作得非常好,可以获取新鲜的(并且多汁的:p)位置值。因此,定义待定意图的行应该如下所示:
Intent intent = new Intent("com.myapp.swarm.LOCATION_READY");
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
0, intent, 0);
//Register for broadcast intents
int minTime = 5000;
int minDistance = 0;
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime,
minDistance, pendingIntent);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
但是,如果出现以下情况,则可以忽略此项:
- 您的目的只是接收一次位置值
- 你设法用一些在你的帖子中看不到的其他方式克服了它
Location
对象