@@ -31,6 +31,7 @@ public class MixpanelFlutterPlugin implements FlutterPlugin, MethodCallHandler {
31
31
private MixpanelAPI mixpanel ;
32
32
private Context context ;
33
33
private JSONObject mixpanelProperties ;
34
+ private FlutterPluginBinding flutterPluginBinding ;
34
35
35
36
private static final Map <String , Object > EMPTY_HASHMAP = new HashMap <>();
36
37
@@ -43,10 +44,9 @@ public MixpanelFlutterPlugin(Context context) {
43
44
44
45
@ Override
45
46
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 ();
50
50
}
51
51
52
52
@ Override
@@ -181,6 +181,13 @@ public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
181
181
}
182
182
183
183
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
+
184
191
final String token = call .argument ("token" );
185
192
if (token == null ) {
186
193
throw new RuntimeException ("Your Mixpanel Token was not set" );
@@ -519,6 +526,10 @@ private void handleGroupUnionProperty(MethodCall call, Result result) {
519
526
520
527
@ Override
521
528
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 ;
523
534
}
524
535
}
0 commit comments