Mapbox の LocationComponent でException発生(解決済み)

Android の Mapbox SDK には LocationComponentと呼ばれるクラスがある。このクラスは、GPSから取得したユーザの現在位置をアプリ上にアイコンとして表示したり、コンパスのように方向付きで表示したり、といったことを可能にしてくれる。これを使用していたところ、下記のようなExceptionに出くわした。

    com.mapbox.mapboxsdk.location.LocationComponentNotInitializedException: The LocationComponent has to be activated with one of the LocationComponent#activateLocationComponent overloads before any other methods are invoked.
        at com.mapbox.mapboxsdk.location.LocationComponent.checkActivationState(LocationComponent.java:1606)
        at com.mapbox.mapboxsdk.location.LocationComponent.setLocationComponentEnabled(LocationComponent.java:504)

実はこれ以前に、mapView.onDestroy() 呼び出し時に LocationComponent で Exception が発生してしまう問題(下記のException)があり、そのため mapView.onDestroy() 呼び出し前に LocationComponent.setLocationComponentEnabled(false)を追加していたのだが、今回はその setLocationComponentEnabled 呼び出し時にExceptionが発生していた。

Fatal Exception: java.lang.IllegalStateException: Calling getSourceAs when a newer style is loading/has loaded.
       at com.mapbox.mapboxsdk.maps.Style.validateState(Style.java:522)
       at com.mapbox.mapboxsdk.maps.Style.getSourceAs(Style.java:132)

実は LocationComponent のいくつかのメソッドは、内部状態をチェックしており、内部状態がActiveではないと呼び出し時に冒頭のExceptionが発生してしまう。今回は setLocationComponentEnabled の呼び出し前に isLocationComponentActivated() の呼び出しを追加することで、Exceptionを回避することができた。