Util for using MapView instead of MapFragment and still avoid boilerplate code to delegate all the activity lifecycle (onCreate, onResume, onPause, onDestroy, etc...) to the MapView.
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import static java.lang.String.format;
public class MapsUtils {
/**
* Allows you to use google maps view (not fragment) without the hassle of
* delegating all the activity lifecycle events to it.
* <p>
* **IMPORTANT** You MUST call this in your activity onCreate() method.
*/
public static void delegateLifecycle(Activity targetActivity, Bundle savedInstanceState, MapView mapView) {
// Make sure the application implements LowMemoryListenableApplication
if (!(targetActivity.getApplication() instanceof LowMemoryListenableApplication)) {
throw new IllegalArgumentException(format("%s must implement LowMemoryListenableApplication delegateLifecycle() to work.",
targetActivity.getApplication().getClass().getCanonicalName()));
}
// Call maps first callbacks
MapsInitializer.initialize(targetActivity);
mapView.onCreate(savedInstanceState);
// Listen for LowMemory on application
LowMemoryListenableApplication application = (LowMemoryListenableApplication) targetActivity.getApplication();
OnLowMemoryListener lowMemoryObserver = mapView::onLowMemory;
application.registerLowMemoryObservable(lowMemoryObserver);
// Register an activity lifecycle callback that redirect each lifecycle event to maps
targetActivity.getApplication().registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) { }
@Override
public void onActivityStarted(Activity activity) { }
@Override
public void onActivityResumed(Activity activity) {
if (activity == targetActivity)
mapView.onResume();
}
@Override
public void onActivityPaused(Activity activity) {
if (activity == targetActivity)
mapView.onPause();
}
@Override
public void onActivityStopped(Activity activity) { }
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
if (activity == targetActivity)
mapView.onSaveInstanceState(outState);
}
@Override
public void onActivityDestroyed(Activity activity) {
if (activity == targetActivity) {
application.unregisterLowMemoryObservable(lowMemoryObserver);
targetActivity.getApplication().unregisterActivityLifecycleCallbacks(this);
mapView.onDestroy();
}
}
});
}
/**
* By implementing this method you must provide a way to listen to
* onLowMemory events in this application.
*/
public static interface LowMemoryListenableApplication {
void registerLowMemoryObservable(OnLowMemoryListener observable);
void unregisterLowMemoryObservable(OnLowMemoryListener observable);
}
public static interface OnLowMemoryListener {
void onLowMemory();
}
}