Need android activity to wait until GPS location obtained

14,944

Solution 1

If you want android activity to wait until GPS location obtained, you might try to use AsyncTask for that. See Android find GPS location once, show loading dialog for the answers. Basically in onPreExecute you can start dialog( it starts before the doInBackground is called). It means you are waiting till the time you can location and showing the dialog. Then in doInBackground you can get the location. After that finishes onPostExecute is called. You can stop is from inside onPostExecute. You can check if the location is not null and then call some other function from inside onPostExecute also if you want.

This might be one way. You can learn a basic example from AsyncTask Android example . You can also start by reading the documentation here.

Some other similar helpful questions:

Wait for current location - GPS - Android Dev

getting location instantly in android

Hope this helps.

Solution 2

Use LocusService 3rd party library! Goto LocusService

By invoking simple function you will able to get your current GPS or Net Location easily....

To solve your problem use this code!

LocusService locusService = new LocusService(this);
locusService.startRealtimeGPSListening(1000);   //Set intervel

locusService.setRealTimeLocationListener(new LocusService.RealtimeListenerService() {
        @Override
        public void OnRealLocationChanged(Location location) {
                if(location!=null){
                  //Do your Stuff here
                  finish();
                }
        }
    });

Solution 3

I faced same issue ,

Solved it, by using Activity life cycle methods.


1)GPS capturing function inside onCreate(Bundle b) method

2) intent or function which in need of GPS Location ,in onStart() method.


So Activity Start from onCreate(bundle) method where GPS location will be captured.Here GPS Altitude,Latitude,Longitude values will be assigned to a global variables.

After that onStart() method will be executed ,in which GPS location global variables will called to do necessary action.


Hope this helped you

Solution 4

Better to use getLastKnownLocation() method. Here is an example of code:

Make your latitude and longitude as a global variable

double longitude;
double latitude;
protected void onCreate(Bundle savedBundle) {
       super.onCreate(savedBundle);
       setContentView(R.layout.activity_receipt_result);
       Objects.requireNonNull(getSupportActionBar()).setElevation(0);

       locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);

       if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    Activity#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for Activity#requestPermissions for more details.
        ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION},1);
    }else{
        Location location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        Log.d("Location: ", "long-lat" + longitude + "-"+ latitude);
    }
}

After you can use the longitude and the latitude variable in the rest of your code.

Share:
14,944
Admin
Author by

Admin

Updated on June 17, 2022

Comments

  • Admin
    Admin almost 2 years

    Sorry for my english. I'm trying to get a single location from GPS to put on global variables latitude, longitude. GPS turns on, but the activity goes on before data is retrieved from GPS.

    My needs in other words... method getCurrentLocation() must finish only if a location has been found and the longitude and latitude variables are filled, so I could use them in other method. I know... user has to wait... I will solve this forward showing something on screen. What should I do? Thank you

    I think I'm skipping stop listening GPS at some place. Where is better?

    Code follows:

    //Method to retrieve coordinates
    public void getCurrentLocation() {
        //Use GPS if possible
        if(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            //assign Listener to GPS
            manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
            Toast.makeText(this, LocationManager.GPS_PROVIDER, Toast.LENGTH_SHORT).show();
        }
        else if(manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){//toherwise, use NETWORK
            //assign Listener to NETWORK
            manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
            Toast.makeText(this, LocationManager.NETWORK_PROVIDER, Toast.LENGTH_SHORT).show();
        }
    }
    
    //Class to store the location recived in two variables
    final class MyLocationListener implements LocationListener {
    
        @Override
        public void onLocationChanged(Location location) {
            //coordinates storing
            latitude = String.valueOf(location.getLatitude());
            longitude = String.valueOf(location.getLongitude());
            Toast.makeText(getApplicationContext(), latitude + longitude, Toast.LENGTH_LONG).show();
        }
    
        @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
        }
    }