Skip to content
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 2.18.0

* Adds GoogleMapsFlutterAndroid.warmup().

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: backticks around the code.

Also, this should provide some client-facing context about what this is, rather than someone needing to go read the API docs to understand what this method is for.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I came up with

* Adds support for warming up the Google Maps SDK 
  via `GoogleMapsFlutterAndroid.warmup()`.

I try to balance the laconic style of the changelog with giving some context, but I feel I'm botching it?


## 2.17.0

* Updates `com.google.android.gms:play-services-maps` to 19.2.0.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@ the issue in the TLHC mode.
| Heatmap.maximumZoomIntensity | x |
| HeatmapGradient.colorMapSize | ✓ |

## Warmup

The first time a map is shown, the Google Maps SDK may briefly block
the main thread, which could cause UI jank.
If you prefer to control when this happens, you can call
`GoogleMapsFlutterAndroid.warmup()` at some point before showing any maps to
pre-warm the SDK. See this plugin's example code for one way of using this API.

Comment thread
filiph marked this conversation as resolved.
[1]: https://pub.dev/packages/google_maps_flutter
[2]: https://flutter.dev/to/endorsed-federated-plugin
[3]: https://docs.flutter.dev/development/platform-integration/android/platform-views
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,19 @@
package io.flutter.plugins.googlemaps;

import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapsSdkInitializedCallback;
import io.flutter.plugin.common.BinaryMessenger;

/** GoogleMaps initializer used to initialize the Google Maps SDK with preferred settings. */
final class GoogleMapInitializer
implements OnMapsSdkInitializedCallback, Messages.MapsInitializerApi {
private static final String TAG = "GoogleMapInitializer";
private final Context context;
private static Messages.Result<Messages.PlatformRendererType> initializationResult;
private boolean rendererInitialized = false;
Expand All @@ -41,6 +44,25 @@ public void initializeWithPreferredRenderer(
}
}

@Override
public void warmup(@NonNull Messages.VoidResult result) {
Log.i(TAG, "Google Maps warmup started.");
try {
// This creates a fake map view in order to trigger the SDK's
// initialization. For context, see
// https://github.com/flutter/flutter/issues/28493#issuecomment-2919150669.
MapView mv = new MapView(context);
mv.onCreate(null);
Comment thread
filiph marked this conversation as resolved.
mv.onResume();
mv.onPause();
mv.onDestroy();
Log.i(TAG, "Maps warmup complete.");
result.success();
} catch (Exception e) {
result.error(new Messages.FlutterError("Could not warm up", e.toString(), null));
}
}

/**
* Initializes map renderer to with preferred renderer type.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7657,6 +7657,14 @@ public interface MapsInitializerApi {
*/
void initializeWithPreferredRenderer(
@Nullable PlatformRendererType type, @NonNull Result<PlatformRendererType> result);
/**
* Asks the Google Maps SDK to do the thread-blocking work it normally does when a map is shown
* for the first time.
*
* <p>This gives the developer the option to move that jank to a different part of the map
* (typically, the app startup, where missed frames aren't going to be noticed).
*/
void warmup(@NonNull VoidResult result);

/** The codec used by MapsInitializerApi. */
static @NonNull MessageCodec<Object> getCodec() {
Expand Down Expand Up @@ -7706,6 +7714,36 @@ public void error(Throwable error) {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.google_maps_flutter_android.MapsInitializerApi.warmup"
+ messageChannelSuffix,
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<>();
VoidResult resultCallback =
new VoidResult() {
public void success() {
wrapped.add(0, null);
reply.reply(wrapped);
}

public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};

api.warmup(resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
}
}
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ void main() {

Completer<AndroidMapRenderer?>? _initializedRendererCompleter;

/// Initializes map renderer to the `latest` renderer type.
/// Initializes map renderer to the `latest` renderer type, and calls
/// [GoogleMapsFlutterAndroid.warmup()].
///
/// The renderer must be requested before creating GoogleMap instances,
/// as the renderer can be initialized only once per application context.
Expand All @@ -100,11 +101,13 @@ Future<AndroidMapRenderer?> initializeMapRenderer() async {

WidgetsFlutterBinding.ensureInitialized();

final GoogleMapsFlutterPlatform platform = GoogleMapsFlutterPlatform.instance;
unawaited((platform as GoogleMapsFlutterAndroid)
final GoogleMapsFlutterAndroid platform =
GoogleMapsFlutterPlatform.instance as GoogleMapsFlutterAndroid;
unawaited(platform
.initializeWithRenderer(AndroidMapRenderer.latest)
.then((AndroidMapRenderer initializedRenderer) =>
completer.complete(initializedRenderer)));
completer.complete(initializedRenderer))
.then((_) => platform.warmup()));

return completer.future;
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform {
/// Creates a new Android maps implementation instance.
GoogleMapsFlutterAndroid({
@visibleForTesting MapsApi Function(int mapId)? apiProvider,
}) : _apiProvider = apiProvider ?? _productionApiProvider;
@visibleForTesting MapsInitializerApi? initializerApi,
}) : _apiProvider = apiProvider ?? _productionApiProvider,
_initializerApi = initializerApi ?? MapsInitializerApi();

/// Registers the Android implementation of GoogleMapsFlutterPlatform.
static void registerWith() {
Expand All @@ -77,6 +79,8 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform {
// A method to create MapsApi instances, which can be overridden for testing.
final MapsApi Function(int mapId) _apiProvider;

final MapsInitializerApi _initializerApi;

/// The per-map handlers for callbacks from the host side.
@visibleForTesting
final Map<int, HostMapMessageHandler> hostMapHandlers =
Expand Down Expand Up @@ -532,16 +536,25 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform {
preferredRenderer = null;
}

final MapsInitializerApi hostApi = MapsInitializerApi();
final PlatformRendererType initializedRenderer =
await hostApi.initializeWithPreferredRenderer(preferredRenderer);
final PlatformRendererType initializedRenderer = await _initializerApi
.initializeWithPreferredRenderer(preferredRenderer);

return switch (initializedRenderer) {
PlatformRendererType.latest => AndroidMapRenderer.latest,
PlatformRendererType.legacy => AndroidMapRenderer.legacy,
};
}

/// Asks the Google Maps SDK to do the thread-blocking work it normally does

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about "Attempts to trigger any thread-blocking work the Google Maps SDK normally does when a map is shown for the first time."

It's not actually asking the SDK to do this; that implies some officially supported API intended for this purpose. Instead it's trying to trigger it via reliance on internal implementation details of the SDK that could change at any time.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really like this, thanks for the suggestion! Implemented.

/// when a map is shown for the first time.
///
/// This gives the developer the option to move that jank to a different
/// part of the map (typically, the app startup, where missed frames
/// aren't going to be noticed).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove the parenthetical here, per the discussion in the README.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Future<void> warmup() async {
await _initializerApi.warmup();
}

Widget _buildView(
int creationId,
PlatformViewCreatedCallback onPlatformViewCreated, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3104,6 +3104,32 @@ class MapsInitializerApi {
return (pigeonVar_replyList[0] as PlatformRendererType?)!;
}
}

/// Asks the Google Maps SDK to do the thread-blocking work it normally does
/// when a map is shown for the first time.
Future<void> warmup() async {
final String pigeonVar_channelName =
'dev.flutter.pigeon.google_maps_flutter_android.MapsInitializerApi.warmup$pigeonVar_messageChannelSuffix';
final BasicMessageChannel<Object?> pigeonVar_channel =
BasicMessageChannel<Object?>(
pigeonVar_channelName,
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
final List<Object?>? pigeonVar_replyList =
await pigeonVar_channel.send(null) as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
throw PlatformException(
code: pigeonVar_replyList[0]! as String,
message: pigeonVar_replyList[1] as String?,
details: pigeonVar_replyList[2],
);
} else {
return;
}
}
}

/// Dummy interface to force generation of the platform view creation params,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -786,6 +786,15 @@ abstract class MapsInitializerApi {
@async
PlatformRendererType initializeWithPreferredRenderer(
PlatformRendererType? type);

/// Asks the Google Maps SDK to do the thread-blocking work it normally does
/// when a map is shown for the first time.
///
/// This gives the developer the option to move that jank to a different
/// part of the map (typically, the app startup, where missed frames
/// aren't going to be noticed).
Comment thread
filiph marked this conversation as resolved.
Outdated
@async

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I missed this in previous review: why is this marked @async? There's no async step in the Java code, it's all synchronous. Without the @async annotation the Java code would be simpler, without the possibility of accidentally not calling the result.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah! Damn, sorry I missed it. The original code was async but then I found out it wouldn't work so I made it synchronous — and promptly forgot about this being async.

Addressed.

void warmup();
}

/// Dummy interface to force generation of the platform view creation params,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: google_maps_flutter_android
description: Android implementation of the google_maps_flutter plugin.
repository: https://github.com/flutter/packages/tree/main/packages/google_maps_flutter/google_maps_flutter_android
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+maps%22
version: 2.17.0
version: 2.18.0

environment:
sdk: ^3.6.0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import 'package:mockito/mockito.dart';

import 'google_maps_flutter_android_test.mocks.dart';

@GenerateNiceMocks(<MockSpec<Object>>[MockSpec<MapsApi>()])
@GenerateNiceMocks(
<MockSpec<Object>>[MockSpec<MapsApi>(), MockSpec<MapsInitializerApi>()])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();

Expand All @@ -32,6 +33,40 @@ void main() {
expect(GoogleMapsFlutterPlatform.instance, isA<GoogleMapsFlutterAndroid>());
});

test('normal usage does not call MapsInitializerApi', () async {
final MockMapsApi api = MockMapsApi();
final MockMapsInitializerApi initializerApi = MockMapsInitializerApi();
final GoogleMapsFlutterAndroid maps = GoogleMapsFlutterAndroid(
apiProvider: (_) => api, initializerApi: initializerApi);
const int mapId = 1;
maps.ensureApiInitialized(mapId);
await maps.init(1);

verifyZeroInteractions(initializerApi);
});

test('initializeWithPreferredRenderer forwards the initialization call',
() async {
final MockMapsApi api = MockMapsApi();
final MockMapsInitializerApi initializerApi = MockMapsInitializerApi();
final GoogleMapsFlutterAndroid maps = GoogleMapsFlutterAndroid(
apiProvider: (_) => api, initializerApi: initializerApi);
await maps.initializeWithRenderer(AndroidMapRenderer.latest);

verify(initializerApi
.initializeWithPreferredRenderer(PlatformRendererType.latest));
});

test('warmup forwards the initialization call', () async {
final MockMapsApi api = MockMapsApi();
final MockMapsInitializerApi initializerApi = MockMapsInitializerApi();
final GoogleMapsFlutterAndroid maps = GoogleMapsFlutterAndroid(
apiProvider: (_) => api, initializerApi: initializerApi);
await maps.warmup();

verify(initializerApi.warmup());
});

test('init calls waitForMap', () async {
final MockMapsApi api = MockMapsApi();
final GoogleMapsFlutterAndroid maps =
Expand Down
Loading