Learn how to retrieve the context for a cordova plugin in Android

The Context class is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc. 

A lot of open source pieces or native functions of Android, requires the Context as a parameter in some functions, in this article you will learn how to retrieve it easily in a Cordova Plugin.

Retrieve context

As first, you need to import the Context class to handle the variable in your code using:

import android.content.Context;

Now that you've just imported the Context class, you can retrieve it using:

Context context = this.cordova.getActivity().getApplicationContext();

Note: you need to use this code within a class that extends the CordovaPlugin class.

Example

The following example shows how to retrieve the context in a Cordova Plugin to show a toast:

package com.ourcodeworld.plugins.MyCustomClassName;

import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;

/*For toast and context*/
import android.content.Context;
import android.widget.Toast;

public class MyCustomClassName extends CordovaPlugin {
    private CallbackContext PUBLIC_CALLBACKS = null;

    @Override
    public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
        PUBLIC_CALLBACKS = callbackContext;
        final JSONObject arg_object = data.getJSONObject(0);

        /*Shows hello world in a Toast*/
        if(action.equals("show_toast")){
            Context context = this.cordova.getActivity().getApplicationContext();
            int duration = Toast.LENGTH_LONG;

            Toast toast = Toast.makeText(context, "Hello World!", duration);
            toast.show();
        }
 
        PluginResult result = new PluginResult(PluginResult.Status.OK, "success");
        result.setKeepCallback(true);
        PUBLIC_CALLBACKS.sendPluginResult(result);

        return true;
    }
}

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors