sky
sky

Reputation: 341

When I write a Flutter plugin, how can I get the android.app.Application object?

When I use Flutter to develop my application, I need use a third-party android SDK.

This SDK needs to init very early before I use other SDK functions and this init function has params which are Application object from android.app.Application.

But how can I get this application object in my plugin.java file so that I can use it to define a function that I can use?

Someone told me that there is an import io.flutter.app.FlutterApplication; class, but it's uneditable, and even if I could edit it, I have nowhere to use it, so I still can't init my SDK.

Here is what I'm thinking, but it's not good enough:

public class FlutterApplication extends Application {
    ....
    @CallSuper
    public void onCreate() {
        super.onCreate();
        MySDK.init(this_application_object, param1, param2)
        FlutterMain.startInitialization(this);
    }
    ....
}

Upvotes: 4

Views: 3341

Answers (2)

Another way is:

override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
  flutterPluginBinding.applicationContext // the context is here
}

Upvotes: 0

Ankit
Ankit

Reputation: 135

You can get the application context like this...

public class CloudSdkPlugin implements MethodCallHandler {

    private static Context context;

     public static void registerWith(Registrar registrar) {
        context=registrar.activity().getApplication();

      }
    }

Upvotes: 3

Related Questions