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

1,888

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();

      }
    }
Share:
1,888
sky
Author by

sky

Updated on December 16, 2022

Comments

  • sky
    sky over 1 year

    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);
        }
        ....
    }
    
    
    • Richard Heap
      Richard Heap over 4 years
      You'd normally have to provide instructions for your plugin user to call this initialisation in their app. See the instructions for firebase_messaging as an example. In your plugin, you'd do this in the example/android app. In onCreate() just use getApplication().