flutterflutter-pluginflutter-platform-channel

Get activity reference in flutter plugin


When I created a flutter plugin, there are two methods in the plugin class by default:

override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding)

and

fun registerWith(registrar: Registrar)

The comment on the file says : It is encouraged to share logic between onAttachedToEngine and registerWith to keep them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called depending on the user's project. onAttachedToEngine or registerWith must both be defined in the same class.

Now, I need to start another activity from here, with activity.startActivityForResult(). It is possible to get a reference to the activity in registerWith(registrar: Registrar) using registrar.activity(). How can I do this in the method onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) ?


Solution

  • Found the solution here.
    Implement ActivityAware and one of its methods is

     override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        this.activity = binding.activity;
      }