Implementazione di Google Analytics per Firebase in Android Webview

1. Introduzione

Ultimo aggiornamento: 2022-02-03

8cef5cc6581b73d0.png

Cosa imparerai

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

Di cosa avrai bisogno

  • Progetto Firebase con SDK Analytics implementato
  • Android Studio versione 4.2+.
  • Un emulatore Android con Android 5.0+.
  • Familiarità con il linguaggio di programmazione Java.
  • Familiarità con il linguaggio di programmazione Javascript.

2. Crea una semplice Webview Web in Android

Aggiunta di Webview nel layout dell'attività

Per aggiungere una WebView alla tua app nel layout, aggiungi il seguente codice al file XML di layout della tua 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, utilizzare loadUrl(). La Webview dovrebbe essere creata sull'attività nera. Ad esempio, lo implementerò sul 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, tuttavia, la tua app deve avere accesso a Internet. Per ottenere l'accesso a Internet, richiedi l'autorizzazione INTERNET nel tuo file manifest. Per esempio:

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

Questo è tutto ciò che serve per un WebView di base che visualizza una pagina web.

Utilizzo di Javascript nelle visualizzazioni Web

se la pagina web che intendi caricare nel tuo WebView utilizza JavaScript, devi abilitare JavaScript per il tuo WebView. Una volta abilitato JavaScript, puoi anche creare interfacce tra il codice dell'app e il codice JavaScript.

JavaScript è disabilitato in una WebView per impostazione predefinita. Puoi abilitarlo tramite WebSettings collegato al tuo WebView. È possibile recuperare WebSettings con getSettings(), quindi abilitare JavaScript con setJavaScriptEnabled().

Per 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 a ponte Javascript

Gestore Javascript

Il primo passaggio per utilizzare Google Analytics in una WebView è creare funzioni JavaScript per inoltrare eventi e proprietà utente al codice nativo. L'esempio seguente mostra come eseguire questa operazione in modo compatibile sia con il codice nativo Android che con quello 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 @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 sei pronto per iniziare a inviare eventi analitici.

4. Invio di eventi tramite l'interfaccia

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

7a00ed1192151b19.png

Dopo aver fatto clic sui pulsanti, chiamerà il mio file "script.js" ed eseguirà 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 abilitare la modalità debug, utilizza i seguenti comandi nella console Android Studio:

adb shell setprop debug.firebase.analytics.app package_name

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

d230debf4ccfddad.png

6. Congratulazioni

Congratulazioni, hai creato con successo una visualizzazione web nella tua app Android. Puoi inviare e misurare gli eventi chiave della canalizzazione nella tua app che avvengono tramite visualizzazioni web. Per sfruttare al meglio tutto ciò, suggeriamo anche di collegarsi 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