How to get Activity from Flutter Android's PlatformView

Viewed 671

Is it possible to get the current activity from my native Android code (as shown in FooView.java's constructor, I need to provide an activity)?

I need FooView.java itself to check for camera permissions and to check if ARCore is installed. I'm fairly new to Flutter and it's platform integration and I couldn't find answers online. If it's a Flutter Plugin the activity is accessible thru registrar.activity(), but I don't have a registrar since I did the non-Plugin approach (I believe it's called App registration).

MainActivity.java

public class MainActivity extends FlutterActivity {
  @Override public void configureFlutterEngine(FlutterEngine flutterEngine) {
    GeneratedPluginRegistrant.registerWith(flutterEngine);
    flutterEngine.getPlatformViewsController().getRegistry().registerViewFactory("fooView", new FooViewFactory());
  }
}

FooView.java

public class FooView implements PlatformView {
  private boolean requestInstall = true;

  FooView(Context context, int id, Map<String, Object> creationParams) {
    Activity someActivity = ?????; // TODO: Find where to get the activity holding the view
    switch (ArCoreApk.getInstance().requestInstall(someActivity, requestInstall)) {
      ...
    }
  }
}
1 Answers

First, change your viewFactory constructor to this to include activity:

class NativeViewFactory(val activity: Activity)

Now change the native View's constructor which in your case is FooView. Change it to this to include activity.

FooView(Activity activity,Context context, int id, Map<String, Object> creationParams)

Now the last part is to replace the following code inside your MainActivity:

flutterEngine.getPlatformViewsController().getRegistry().registerViewFactory("fooView", new FooViewFactory());

with this:

flutterEngine.getPlatformViewsController().getRegistry().registerViewFactory("fooView", new FooViewFactory(getActivity()));
Related