Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android when exactly is onLocationChanged called

Tags:

android

It seems for me it is getting called the first time the activity starts, just after onCreate, it then seems to be called at random intervals, whether I move or not???

Regardless of that is it simply called automatically if I have code like this in the onCreate method?

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();

Is that right???

Cheers, Mike.


1 Answers

Your question is not clear initially.Your code and title are not matching. I am giving answer for your title only.

You have to register Location Listener for your Location Manager, then only onLocationChanged() will be called according the settings you supplied while registering location listener.

See below code how to do that. I used GPS Provider, you can use any provider based on criteria also.

LocationManger lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // TODO Auto-generated method stub
            }
            @Override
            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub
            }
            @Override
            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub
            }
            @Override
            public void onStatusChanged(String provider, int status,
                    Bundle extras) {
                // TODO Auto-generated method stub
            }           
        });

Coming to your question, onLocationChanged() will be called if the current location update is not matching with last known location.

The updated location will be changed for every minTime (in my case 1000 milli sec) and also if device moved minDistance (in my case 0 meters) distance.

I hope you will understand this.

like image 105
Yugandhar Babu Avatar answered Sep 15 '25 06:09

Yugandhar Babu