Android:使用 LocationManager.requestLocationUpdates() 时如何从 Int

时间:2023-03-22
本文介绍了Android:使用 LocationManager.requestLocationUpdates() 时如何从 Intent 捆绑包中获取位置信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

I am trying to use Android's LocationManager requestLocationUpdates. Everything is working until I try to extract the actual location object that in my broadcast receiver. Do I need to specifically define the "extras" to my custom intent so that the Android LocationManager before I pass it to requestLocationUpdates so it knows how to add it into the intent, or will it create the extras-bundle regardless when it passes the fired intent to the broadcast receiver?

我的代码如下所示:

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

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

I have a broadcast receiver that is defined in the manifesto as:

<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"对象即将为空.

My "loc" object is coming up null.

推荐答案

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

OK, I managed to fix it by changing the KEY_LOCATION_CHANGED in the broadcast receiver code to:

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

这篇关于Android:使用 LocationManager.requestLocationUpdates() 时如何从 Intent 捆绑包中获取位置信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:从坐标获取国家? 下一篇:Android - 可靠地获取当前位置

相关文章