Search code examples
javaandroidcapacitor-plugin

Capacitor/Android Question: How to obtain current Context?


I am developing a Capacitor (4) plugin and need to access Android system services, which requires referencing the current Context. How do I obtain the context within the scope of the plugin?

Thank you.


Solution

  • You should be able to call this.getActivity().getApplicationContext() in a class that extends com.getcapacitor.Plugin.

    For example, see below custom plugin code:

    package com.example.mypackage;
    
    import com.getcapacitor.JSObject;
    import com.getcapacitor.Plugin;
    import com.getcapacitor.PluginCall;
    import com.getcapacitor.PluginMethod;
    import com.getcapacitor.annotation.CapacitorPlugin;
    
    @CapacitorPlugin(name = "MyPackage")
    public class MyPackagePlugin extends Plugin {
    
        private MyPackage implementation = new MyPackage(this.getActivity().getApplicationContext());
    
        @PluginMethod
        public void echo(PluginCall call) {
            String value = call.getString("value");
    
            JSObject ret = new JSObject();
            ret.put("value", implementation.echo(value));
            call.resolve(ret);
        }
    }
    

    UPDATE

    In the more recent versions of Capacitor you can also call the getContext method which is defined in the built-in Plugin.java file.

    /**
     * Get the main {@link Context} for the current Activity (your app)
     * @return the Context for the current activity
     */
    public Context getContext() {
        return this.bridge.getContext();
    }
    

    Reference link: Plugin source

    Hope that helps!