-3

I am new to Android and I would like to get the device current location co-ordinates and return it.

This following function is called anytime the location is needed.

PSEUDOCODE

    Public arrays GetLocation(){
     // GET LATITUDE
     // GET LONGITUDE
     LocationArray = [LATITUDE] [LONGITUDE]
     return LocationArray 
    }

How can this be implemented efficiently. Thanks in advance

Udo
  • 1,129
  • 3
  • 15
  • 30

1 Answers1

2
public double[] getLocation()
{
    double[] latlon = new double[2];
 // Get the location manager
 LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
 Criteria criteria = new Criteria();
 String bestProvider = locationManager.getBestProvider(criteria, false);
 Location location = locationManager.getLastKnownLocation(bestProvider);
 Double lat,lon;
 try {
   lat = location.getLatitude ();
   lon = location.getLongitude ();
   latlon[0] = lat;
   latlon[1] = lon;
   return latlon;
 }
 catch (NullPointerException e){
     e.printStackTrace();
   return null;
 }
}
Solution
  • 604
  • 4
  • 10
  • will this get the device's current location or the last know location ? – Udo Feb 25 '14 at 09:14
  • it gives you Last know location, if you need fresh location than use above answer given by @degvesh patel. On app launch start gps service and get location when you need. – Solution Feb 25 '14 at 09:17
  • The array 'latlon' was created without specifying a size, is that possible in java ? – Udo Feb 25 '14 at 09:42
  • so that means as much data can be stored in the array ?? – Udo Feb 25 '14 at 09:54
  • thanks! but please can you tell me how i can call the method by @degvesh Patel in another class ? – Udo Feb 25 '14 at 10:13
  • He had already mention in second block of code. – Solution Feb 25 '14 at 10:17
  • when i tried it i get the error: AndroidGPSTrackingActivity cannot be resolved to a type – Udo Feb 25 '14 at 10:21
  • 1
    you can replace first line with below. gps = new GPSTracker(getApplicationContext()); If it is help than mark up in this comment. – Solution Feb 25 '14 at 10:26