How to pass data from Cordova Native Android to hosted web app

41 views
0

We have successful built a Cordova Android app to wrap our mobile web app. This all works very well. Here is the start up code:

package magical.magicalwebapp;

import android.os.Bundle;
import org.apache.cordova.*;

public class MainActivity extends CordovaActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // enable Cordova apps to be started in the background
        Bundle extras = getIntent().getExtras();
        if (extras != null && extras.getBoolean("cdvStartInBackground", false)) {
            moveTaskToBack(true);
        }

        // Set by <content src="index.html" /> in config.xml
        loadUrl(launchUrl);
    }
}

We have the Firebase Javascript library installed in the web app and that works correctly when the web app is executed as a normal web page.

Unfortunately, we could not get the Firebase JS code to execute when running inside the Cordova app so we then installed the Cordova Firebase Plugin.

The Cordova Firebase plugin connects correctly to FCM and gets an Instance ID (Token) used for messaging, however, we cannot figure out how to pass the Instance Id to the Web App.

For the web app user to receive relevant messages we need to register the FCM Instance ID on our web server/application server linked to the username used when the user logged into the web app.

We need a method to pass the Instance ID to the web app – eg by setting a Javascript variable.

Here is the Firebase Instance ID Java code:

public class FirebasePluginInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "FirebasePlugin";

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        FirebasePlugin.sendToken(refreshedToken);
    }
}