Android: How to get location information from intent bundle extras when using LocationManager.requestLocationUpdates()

前端 未结 2 1783
一生所求
一生所求 2020-12-05 00:50

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.

相关标签:
2条回答
  • 2020-12-05 01:26

    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(); 
        }
    }
    
    0 讨论(0)
  • 2020-12-05 01:41

    i ve tried to code and test the solution you proposed, since i am facing similar problems concerning proximity alerts and intents carrying location objects. According the information you provided, you managed to overcome the null object retrieval, on the BroadcastReceiver's side. What you might did not observe is that now you should be receiving the same location as the one your intent was first created (also seen it as: intent caching problem).

    In order to overcome this problem, i used FLAG_CANCEL_CURRENT, as being proposed by many people here and it works pretty fine, fetching fresh (and juicy :P) location values. So the line defining your pending intent should look like this:

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

    However, you can ignore this if:

    • your purpose was just to receive a location value once
    • you managed to overcome it in some other way not visible in your post
    0 讨论(0)
提交回复
热议问题