Skip to content

Commit f658397

Browse files
committed
make onAttachedEngine ligtweight and lazily create MethodChannel
1 parent db17641 commit f658397

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

android/src/main/java/com/mixpanel/mixpanel_flutter/MixpanelFlutterPlugin.java

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ public class MixpanelFlutterPlugin implements FlutterPlugin, MethodCallHandler {
3131
private MixpanelAPI mixpanel;
3232
private Context context;
3333
private JSONObject mixpanelProperties;
34+
private FlutterPluginBinding flutterPluginBinding;
3435

3536
private static final Map<String, Object> EMPTY_HASHMAP = new HashMap<>();
3637

@@ -43,10 +44,9 @@ public MixpanelFlutterPlugin(Context context) {
4344

4445
@Override
4546
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
46-
channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "mixpanel_flutter",
47-
new StandardMethodCodec(new MixpanelMessageCodec()));
48-
context = flutterPluginBinding.getApplicationContext();
49-
channel.setMethodCallHandler(this);
47+
// Store references for lazy initialization to avoid ANR during plugin registration
48+
this.flutterPluginBinding = flutterPluginBinding;
49+
this.context = flutterPluginBinding.getApplicationContext();
5050
}
5151

5252
@Override
@@ -181,6 +181,13 @@ public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
181181
}
182182

183183
private void handleInitialize(MethodCall call, Result result) {
184+
// Lazy initialization of MethodChannel to avoid ANR
185+
if (channel == null && flutterPluginBinding != null) {
186+
channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "mixpanel_flutter",
187+
new StandardMethodCodec(new MixpanelMessageCodec()));
188+
channel.setMethodCallHandler(this);
189+
}
190+
184191
final String token = call.argument("token");
185192
if (token == null) {
186193
throw new RuntimeException("Your Mixpanel Token was not set");
@@ -519,6 +526,10 @@ private void handleGroupUnionProperty(MethodCall call, Result result) {
519526

520527
@Override
521528
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
522-
channel.setMethodCallHandler(null);
529+
if (channel != null) {
530+
channel.setMethodCallHandler(null);
531+
channel = null;
532+
}
533+
flutterPluginBinding = null;
523534
}
524535
}

0 commit comments

Comments
 (0)