Implementazione di Google Analytics per Firebase in Android WebView

1. Introduzione

Ultimo aggiornamento: 03/02/2022

8cef5cc6581b73d0.png

Cosa imparerai a fare

  • Come creare una WebView molto semplice in Android
  • Come inviare eventi Webview a Firebase

Che cosa ti serve

  • Progetto Firebase con l'SDK Analytics implementato
  • Android Studio versione 4.2 o successive.
  • Un emulatore Android con Android 5.0 o versioni successive.
  • Familiarità con il linguaggio di programmazione Java.
  • Familiarità con il linguaggio di programmazione JavaScript.

2. Crea una semplice visualizzazione web in Android

Aggiunta di WebView nel layout dell'attività

Per aggiungere una WebView all'app nel layout, aggiungi il seguente codice al file XML di layout dell'attività:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".WebActivity"
>
  <WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
  />
</androidx.constraintlayout.widget.ConstraintLayout>;

Aggiunta di una WebView in onCreate()

Per caricare una pagina web in WebView, utilizza loadUrl(). WebView deve essere creato in un'attività in background. Ad esempio, implementerò questa operazione nel metodo onCreate :

public class WebActivity extends AppCompatActivity {
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        // Navigate to site
        myWebView.loadUrl("https://bittererhu.glitch.me");
 }
}

Prima che funzioni, però, la tua app deve avere accesso a internet. Per ottenere l'accesso a internet, richiedi l'autorizzazione INTERNET nel file manifest. Ad esempio:

<uses-permission android:name="android.permission.INTERNET" />

È tutto ciò che ti serve per una WebView di base che visualizza una pagina web.

Utilizzo di JavaScript nelle WebView

Se la pagina web che prevedi di caricare nel componente WebView utilizza JavaScript, devi attivare JavaScript per il componente WebView. Una volta attivato JavaScript, puoi anche creare interfacce tra il codice dell'app e il codice JavaScript.

JavaScript è disattivato in una WebView per impostazione predefinita. Puoi attivarlo tramite WebSettings collegato a WebView. Puoi recuperare WebSettings con getSettings(), quindi attivare JavaScript con setJavaScriptEnabled().

Ad esempio:

WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

Attività aggiornata :

public class WebActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        WebView myWebView = (WebView) findViewById(R.id.webview);
        if(myWebView != null) {
            WebSettings webSettings = myWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);
        }
        // Navigate to site
        myWebView.loadUrl("https://bittererhu.glitch.me");
  }
}

be627fcc51a6179f.png

3. Implementazione dell'interfaccia bridge JavaScript

Gestore JavaScript

Il primo passaggio per utilizzare Google Analytics in una WebView consiste nel creare funzioni JavaScript per inoltrare eventi e proprietà utente al codice nativo. L'esempio seguente mostra come eseguire questa operazione in modo compatibile con il codice nativo di Android e Apple:

In questo esempio ho creato un file JavaScript denominato script.js che include quanto segue :

function logEvent(name, params) {
  if (!name) {
    return;
  }
  if (window.AnalyticsWebInterface) {
    // Call Android interface
    window.AnalyticsWebInterface.logEvent(name, JSON.stringify(params));
  } else if (window.webkit
      && window.webkit.messageHandlers
      && window.webkit.messageHandlers.firebase) {
    // Call iOS interface
    var message = {
      command: 'logEvent',
      name: name,
      parameters: params
    };
    window.webkit.messageHandlers.firebase.postMessage(message);
  } else {
    // No Android or iOS interface found
    console.log("No native APIs found.");
  }
}


function setUserProperty(name, value) {
  if (!name || !value) {
    return;
  }

  if (window.AnalyticsWebInterface) {
    // Call Android interface
    window.AnalyticsWebInterface.setUserProperty(name, value);
  } else if (window.webkit
      && window.webkit.messageHandlers
      && window.webkit.messageHandlers.firebase) {
    // Call iOS interface
    var message = {
      command: 'setUserProperty',
      name: name,
      value: value
   };
    window.webkit.messageHandlers.firebase.postMessage(message);
  } else {
    // No Android or iOS interface found
    console.log("No native APIs found.");
  }
}

Interfaccia nativa

Per richiamare il codice Android nativo da JavaScript, implementa una classe con metodi contrassegnati con @JavaScriptInterface: nell'esempio seguente ho creato una nuova classe Java chiamata AnalyticsWebInterfcae.java:

public class AnalyticsWebInterface {

    public static final String TAG = "AnalyticsWebInterface";
    private FirebaseAnalytics mAnalytics;

    public AnalyticsWebInterface(Context context) {
        mAnalytics = FirebaseAnalytics.getInstance(context);
    }

    @JavascriptInterface
    public void logEvent(String name, String jsonParams) {
        LOGD("logEvent:" + name);
        mAnalytics.logEvent(name, bundleFromJson(jsonParams));
    }

    @JavascriptInterface
    public void setUserProperty(String name, String value) {
        LOGD("setUserProperty:" + name);
        mAnalytics.setUserProperty(name, value);
    }

    private void LOGD(String message) {
        // Only log on debug builds, for privacy
        if (BuildConfig.DEBUG) {
            Log.d(TAG, message);
        }
    }

    private Bundle bundleFromJson(String json) {
        // ...
    }
}

Once you have created the native interface, register it with your WebView so that it is visible to JavaScript code running in the WebView:

// Only add the JavaScriptInterface on API version JELLY_BEAN_MR1 and above, due to
// security concerns, see link below for more information:
// https://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    mWebView.addJavascriptInterface(
            new AnalyticsWebInterface(this), AnalyticsWebInterface.TAG);
} else {
    Log.w(TAG, "Not adding JavaScriptInterface, API Version: " + Build.VERSION.SDK_INT);
}

Codice finale :

// [START analytics_web_interface]
public class AnalyticsWebInterface {

    public static final String TAG = "AnalyticsWebInterface";
    private FirebaseAnalytics mAnalytics;

    public AnalyticsWebInterface(Context context) {
        mAnalytics = FirebaseAnalytics.getInstance(context);
    }
    @JavascriptInterface
    public void logEvent(String name, String jsonParams) {
        LOGD("logEvent:" + name);
        mAnalytics.logEvent(name, bundleFromJson(jsonParams));
    }
    @JavascriptInterface
    public void setUserProperty(String name, String value) {
        LOGD("setUserProperty:" + name);
        mAnalytics.setUserProperty(name, value);
    }
    private void LOGD(String message) {
        // Only log on debug builds, for privacy
        if (BuildConfig.DEBUG) {
            Log.d(TAG, message);
        }
    }
    private Bundle bundleFromJson(String json) {
        // [START_EXCLUDE]
        if (TextUtils.isEmpty(json)) {
            return new Bundle();
        }

        Bundle result = new Bundle();
        try {
            JSONObject jsonObject = new JSONObject(json);
            Iterator<String> keys = jsonObject.keys();

            while (keys.hasNext()) {
                String key = keys.next();
                Object value = jsonObject.get(key);
                if (value instanceof String) {
                    result.putString(key, (String) value);
                } else if (value instanceof Integer) {
                    result.putInt(key, (Integer) value);
                } else if (value instanceof Double) {
                    result.putDouble(key, (Double) value);
                } else {
                    Log.w(TAG, "Value for key " + key + " not one of [String, Integer, Double]");
                }
            }
        } catch (JSONException e) {
            Log.w(TAG, "Failed to parse JSON, returning empty Bundle.", e);
            return new Bundle();
        }
        return result;
        // [END_EXCLUDE]
    }

Ora hai configurato l'interfaccia JavaScript e puoi iniziare a inviare eventi di analisi.

4. Invio di eventi tramite l'interfaccia

Come puoi vedere qui, la mia WebView è molto semplice: ha tre pulsanti, due che registrano un evento e l'altro che registra una proprietà utente:

7a00ed1192151b19.png

Quando faccio clic sui pulsanti, viene chiamato il file "script.js" ed eseguito il seguente codice :

document.getElementById("event1").addEventListener("click", function() {
    console.log("event1");
    logEvent("event1", { foo: "bar", baz: 123 });
});

document.getElementById("event2").addEventListener("click", function() {
  console.log("event2");
    logEvent("event2", { size: 123.456 });
});

document.getElementById("userprop").addEventListener("click", function() {
    console.log("userprop");
    setUserProperty("userprop", "custom_value");
});

File script.js finale :

/* If you're feeling fancy you can add interactivity 
    to your site with Javascript */

// prints "hi" in the browser's dev tools console
console.log("hi");

// [START log_event]
function logEvent(name, params) {
  if (!name) {
    return;
  }

  if (window.AnalyticsWebInterface) {
    // Call Android interface
    window.AnalyticsWebInterface.logEvent(name, JSON.stringify(params));
  } else if (window.webkit
      && window.webkit.messageHandlers
      && window.webkit.messageHandlers.firebase) {
    // Call iOS interface
    var message = {
      command: 'logEvent',
      name: name,
      parameters: params
    };
    window.webkit.messageHandlers.firebase.postMessage(message);
  } else {
    // No Android or iOS interface found
    console.log("No native APIs found.");
  }
}
// [END log_event]

// [START set_user_property]
function setUserProperty(name, value) {
  if (!name || !value) {
    return;
  }

  if (window.AnalyticsWebInterface) {
    // Call Android interface
    window.AnalyticsWebInterface.setUserProperty(name, value);
  } else if (window.webkit
      && window.webkit.messageHandlers
      && window.webkit.messageHandlers.firebase) {
    // Call iOS interface
    var message = {
      command: 'setUserProperty',
      name: name,
      value: value
   };
    window.webkit.messageHandlers.firebase.postMessage(message);
  } else {
    // No Android or iOS interface found
    console.log("No native APIs found.");
  }
}
// [END set_user_property]

document.getElementById("event1").addEventListener("click", function() {
    console.log("event1");
    logEvent("event1", { foo: "bar", baz: 123 });
});

document.getElementById("event2").addEventListener("click", function() {
  console.log("event2");
    logEvent("event2", { size: 123.456 });
});

document.getElementById("userprop").addEventListener("click", function() {
    console.log("userprop");
    setUserProperty("userprop", "custom_value");
});

Questo è il modo di base per inviare eventi ad Analytics

5. Eseguire il debug degli eventi WebView in Firebase

Il debug degli eventi WebView nella tua app funziona allo stesso modo del debug di qualsiasi parte nativa del tuo SDK :

Per attivare la modalità di debug, utilizza i seguenti comandi nella console di Android Studio:

adb shell setprop debug.firebase.analytics.app package_name

Una volta fatto, puoi testare e vedere i tuoi eventi Webview prendere vita :

d230debf4ccfddad.png

6. Complimenti

Congratulazioni, hai creato correttamente una WebView nella tua app per Android. Puoi inviare e misurare gli eventi chiave del funnel nella tua app che si svolgono tramite WebView. Per sfruttare al meglio questa funzionalità, ti consigliamo anche di connetterti a Google Ads e di importare questi eventi come conversioni.

Hai imparato

  • Come inviare eventi WebView a Firebase
  • Come configurare e creare una semplice WebView in Android

Documenti di riferimento