Reputation: 807
I am trying to access the activity reference in a Flutter Plugin written in Kotlin when I press my FAB within Flutter.
My class is ActivityAware
Here is the code: Kotlin:
lateinit var myActivity: Activity
//Method called by ActivityAware plugins to fetch the activity on re-initialization
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
this.myActivity = binding.activity
}
//Method called by ActivityAware plugins to fetch the activity on initialization
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
this.myActivity = binding.activity
}
//With this method is called from Flutter to check if the Activity is accessible.
//In this case it is always returning null/ not initialized
//It prints "FAILED AGAIN!!"
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == "checkForActivity") {
if(::myActivity.isInitialized){
System.out.println("I FOUND IT!!")
}else{
System.out.println("FAILED AGAIN!!")
}
return
} else {
result.notImplemented()
}
}
The dart code (Flutter):
//This Flutter class is run whenever you press a button to check for the Activity in Native Kotlin.
static const MethodChannel _channel =
const MethodChannel('sphinx_plugin');
static Future<bool> get checkForActivity async {
final bool isready = await _channel.invokeMethod('checkForActivity');
return isready;
}
Upvotes: 1
Views: 1295
Reputation: 807
I found a solution.
lateinit var myplugin: MyPlugin()
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
myplugin = MyPlugin()
val channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "my_plugin")
channel.setMethodCallHandler(myplugin)
}
//This is where I was going wrong..The reference was being lost somewhere
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
myplugin.myActivity = binding.activity
}
By setting:
myplugin.myActivity
I was able to find the activity reference later. Anyways thanks :)
Upvotes: 2