Get activity reference in flutter plugin

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

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

Note:

you can get reference to activity by implementing ActivityAware interface but if you setMethodCallHandler(...) in onAttachToEngine() method onAttachToActivity() will never be called and you can never get access to activity

take a look at below examples

WHAT DOES NOT WORK : in below examples onAttachToActivity() is never called

class AndroidLongTaskPlugin : FlutterPlugin, ActivityAware {
  private var activity: FlutterActivity? = null

  

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    //activity is null here 
    //also onAttachToActivity will never be called because we are calling setMethodHandler here
    channel = MethodChannel(binaryMessenger, CHANNEL_NAME)
    channel.setMethodCallHandler { call, result ->
        //our code
    }

  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    channel?.setMethodCallHandler(null)
  }

  override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    activity = binding.activity as FlutterActivity
  }

  //rest of the methods
}

HERE IS A WORKING EXAMPLE :

class MyPlugin : FlutterPlugin, ActivityAware {
  private var activity: FlutterActivity? = null
  private var binaryMessenger: BinaryMessenger? = null

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    binaryMessenger = flutterPluginBinding.binaryMessenger
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    Log.d("DART/NATIVE", "onDetachedFromEngine")
    channel?.setMethodCallHandler(null)
  }

  override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    Log.d("DART/NATIVE", "onAttachedToActivity")
    activity = binding.activity as FlutterActivity
    //here we have access to activity
    //also make sure to setMethodCallHandler here
    channel.setMethodCallHandler { call, result ->
        //our code
    }
  }

  //rest of the methods
}