【问题标题】:Android: How to get location information from intent bundle extras when using LocationManager.requestLocationUpdates()Android:使用 LocationManager.requestLocationUpdates() 时如何从 Intent 捆绑包中获取位置信息
【发布时间】:2024-01-11 09:23:01
【问题描述】:

我正在尝试使用 Android 的 LocationManager requestLocationUpdates。一切正常,直到我尝试提取广播接收器中的实际位置对象。我是否需要专门为我的自定义意图定义“附加”,以便 Android LocationManager 在我将其传递给 requestLocationUpdates 之前知道如何将其添加到意图中,或者它是否会创建附加捆绑包,无论何时通过触发广播接收者的意图?

我的代码如下所示:

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);

我有一个广播接收器,它在宣言中定义为:

<receiver android:name=".LocationReceiver">
    <intent-filter>
        <action android:name="com.myapp.swarm.LOCATION_READY" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

广播接收器类为:

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("KEY_LOCATION_CHANGED");

    Toast.makeText(context, loc.toString(), Toast.LENGTH_SHORT).show(); 
    }
}

我的“loc”对象即将为空。

【问题讨论】:

  • 记住 NULL CHECK - 并非所有这些意图都包含 Location 对象

标签: android geolocation intentfilter android-intent


【解决方案1】:

好的,我设法通过将广播接收器代码中的 KEY_LOCATION_CHANGED 更改为:

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(); 
    }
}

【讨论】:

    【解决方案2】:

    我已尝试对您提出的解决方案进行编码和测试,因为我在接近警报和携带位置对象的意图方面面临类似问题。根据您提供的信息,您设法在 BroadcastReceiver 方面克服了空对象检索。您可能没有观察到的是,现在您应该收到与您的意图首次创建的位置相同的位置(也将其视为:意图缓存问题)。

    为了克服这个问题,我使用了 FLAG_CANCEL_CURRENT,正如这里的许多人所建议的那样,它工作得很好,可以获取新鲜(多汁:P)的位置值。因此,定义待处理意图的行应如下所示:

    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
        0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    

    但是,如果出现以下情况,您可以忽略它:

    • 您的目的只是接收一次位置值
    • 您设法以其他在您的帖子中不可见的方式克服了它

    【讨论】: