Search code examples
androidoncreateactivity-lifecycleonstart

Need help understanding where to put a piece of code, onCreate()/OnStart


I've tried to have a look at the acitivity lifecycle but I still don't understand where to put my code.

  1. In my onCreate() I get the GPS Location.
  2. Sometime later in the application, the Camera Intent is called, and then dismissed.
  3. The GPS Location is retrieved again (I guess onCreate() is being performed again?)

I only want the GPS Location to be retrieved once, at the very start of the application once started.


Solution

  • See my answer about why you can't just "get" a GPS position for some background. Getting the GPS position once in your onCreate() method (with lazy initialization checks to see if you've already got the GPS coordinate in case of multiple calls to onCreate()) may not be the right approach for your application, and could cause your application to be forcibly closed by the Android OS.

    If you've determined that the device's last known location is always good enough for your application then calling it each time your onCreate() method is called is going to be fine as it does not need to use the GPS circuitry. Therefore if the last known location is good enough then simply request it each and every time the onCreate() method is called and avoid the complexity of lazy initialization type sof checks.

    If the last known location is not always good enough for your application then you cannot reliably wait for the fix in the onCreate() method as you run the risk of the location fix taking too long, causing the Android system to force close your unresponsive app because it did not return from the onCreate() method in time. Instead you need to kick off a background asynch task within the onCreate() method (checking that you don't already have such an async task running) that starts listening for location updates until a good enough fix is received and then remembers that location, stopping the location listeners and hence turning off the GPS circuitry. Use code along the lines of:

    private MyAsynchGpsLocationListener mGpsListener = null;
    
    public ... onCreate() {
      if (mGpsListener == null) {
        mGpsListener = new MyAsynchGpsLocationListener();
        mGpsListener.start();
      }
    }
    
    someMethod() {
      if (mGpsListener != null) {
        Location myLocation = mGpsListener.getLocation();
        if (myLocation != null) {
          // Do something with a "good enough" location
        }
      }
    }