开发者

location listener

I am using location listener to get long & lat for my android application.

I am working with the following code:

public Location getLastKnownLocation()
{
 Location location=null;
 try
 {
 // Get the location manager
 mLocMgr = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
 // List all providers:
 // List<String> providers = mLocMgr.getAllProviders();

 Criteria criteria = new Criteria();
 bestProvider = mLocMgr.getBestProvider(criteria, false);
 location = mLocMgr.getLastKnownLocation(bestProvider);
 if(location==null)
 {
  Thread.sleep(5000);
  location=mLocMgr.getLastKnownLocation(bestProvider);
 }
 }
 catch(Exception e)
 {
  Log.i("program", e.getMessage());
 }
 return location;
}

public Location updateCurrentLocation()
{
 Location mLoc=null;
 try
 {
 mLoc=getLastKnownLocation();
 mlocListener = new LocListener(); 
 mLocMgr.requestLocationUpdates(bestProvider, 0, 0, mlocListener);
 mLoc=getLastKnownLocation();
 }
 catch(Exception e)
 {
  Log.e("program", e.getMessage());
 }
 return mLoc;
}

It is working absolutely fine. But facing the problem when we switched off the devic开发者_高级运维e and start it again. Then I am getting the location null. However after starting the google map, it starts working again. So Could you please guys help me out on this because I don't want start the google map before starting my application. Thanking you for support!


Your getLastKnownLocation method is likely to fail when you power off and power on your device.

And, I see that, you are calling it before you subscribe to location update lister:

 mLoc=getLastKnownLocation();  //<<<<<<<<<<<<<
 mlocListener = new LocListener(); 
 mLocMgr.requestLocationUpdates(bestProvider, 0, 0, mlocListener);

Why do you need to call getLastKnownLocation() ? It will not work immediately when you start your device.

When you are using Google map, it is gracefully trying to listen to location update. And, once it gets atleast one location update, then your getLastKnownLocation will start working.

I see that your architecture need re-thinking (if your method names are appropriate)

This should be called ONLY ONCE, in some appropriate location, when your app initiates.

mLocMgr.requestLocationUpdates(bestProvider, 0, 0, mlocListener);

Then, do whatever update you need in onLocationChanged(Location location)


Little Flyffy Location library: http://code.google.com/p/little-fluffy-location-library/

Simple, fast, easy!

this library notify your location updates.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜