Search code examples
androidgoogle-mapslocation-client

App Crash due to Location Client Illegal State


I've got a basic app that uses Google Maps to place a custom marker on the last known location of the device. The app crashes pretty frequently due to an Illegal State Exception thrown by the location client.

java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.

This is usually caused when an Asynctask finishes and then calls an update to the map with new info but gets interrupted due to pausing the activity. I've tried setting a simple boolean check to determine if the client is connected before attempting an update.

if (servicesConnected() && locClientConnected)  {
        loc = lClient.getLastLocation();
//code to draw circle
}

but this seems to have no effect on the ANR/crash so it executes while the activity is active but most not complete before this is called:

protected void onPause()    {
    lClient.disconnect();
    super.onPause();
}

Would it be good practice to remove the disconnect here and allow it to complete? or would that even make a difference? I'm hoping someone has ran into this issue with Location client. :)


Solution

  • Possible solutions:

    1. Use Loaders instead of AsyncTask to avoid this behaviour.
    2. Check activity state before draw

      void onPause(){
          allowDraw = false;
          ...
      }
      
      void onResume(){
          allowDraw  = true;
          ...
      }
      
      if (servicesConnected() && locClientConnected && allowDraw)  {
          loc = lClient.getLastLocation();
          //code to draw circle
      }
      
    3. Use try catch block :)