Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

geolocation - Android: How to get location information from intent bundle extras when using 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?

My code looks like this:

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>

And the broadcast receiver class as:

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

My "loc" object is coming up null.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...