在 Android Webview 中實作 Google Analytics for Firebase

一、簡介

最後更新: 2022-02-03

8cef5cc6581b73d0.png

你將學到什麼

  • 如何在Android中建立一個非常簡單的Webview
  • 如何將 Webview 事件傳送到 Firebase

你需要什麼

  • 實施了 Analytics SDK 的 Firebase 項目
  • Android Studio 版本 4.2+。
  • 帶有 Android 5.0+ 的 Android 模擬器。
  • 熟悉 Java 程式語言。
  • 熟悉 Javascript 程式語言。

2.在Android中建立一個簡單的Web Webview

在activity佈局中新增Webview

若要將 WebView 新增至應用程式的佈局中,請將下列程式碼新增至 Activity 的佈局 XML 檔案中:

<?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>;

在 onCreate() 中新增 WebView

若要在 WebView 中載入網頁,請使用 loadUrl()。 Webview 應該在黑色活動上建立例如我將在 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");
 }
}

然而,在此之前,您的應用程式必須能夠存取互聯網。若要存取 Internet,請在清單檔案中請求 INTERNET 權限。例如:

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

這就是顯示網頁的基本 WebView 所需的全部內容。

在 Web 視圖中使用 Javascript

如果您打算在 WebView 中載入的網頁使用 JavaScript,則必須為 WebView 啟用 JavaScript。啟用 JavaScript 後,您還可以在應用程式程式碼和 JavaScript 程式碼之間建立介面。

預設情況下,WebView 中會停用 JavaScript。您可以透過附加到 WebView 的 WebSettings 啟用它。您可以使用 getSettings() 檢索 WebSettings,然後使用 setJavaScriptEnabled() 啟用 JavaScript。

例如:

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

更新活動:

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. 實作Javascript橋接接口

JavaScript 處理程序

在 WebView 中使用 Google Analytics 的第一步是建立 JavaScript 函數以將事件和使用者屬性轉送到本機程式碼。以下範例展示如何以與 Android 和 Apple 本機程式碼相容的方式執行此操作:

在此範例中,我建立了一個名為 script.js 的 Javascript 文件,其中包含以下內容:

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.");
  }
}

原生介面

要從 JavaScript 呼叫本機 Android 程式碼,請實作一個帶有標記為@JavaScriptInterface的方法的類別:在下面的範例中,我建立了一個名為:AnalyticsWebInterfcae.java 的新 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);
}

最終代碼:

// [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]
    }

現在您已經設定了 Javascript 介面,現在可以開始發送分析事件了。

4. 透過介面發送事件

正如您在這裡看到的,我的 Webview 非常簡單,它有三個按鈕,其中兩個按鈕將記錄事件,另一個按鈕將記錄使用者屬性:

7a00ed1192151b19.png

單擊按鈕後,它將調用我的“script.js”檔案並執行以下程式碼:

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");
});

最終的 script.js 檔案:

/* 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");
});

這是將事件傳送到 Analytics 的基本方法

5. 在 Firebase 中偵錯 Webview 事件

在應用程式中偵錯 Webview 事件的方式與偵錯 SDK 的任何本機部分的方式相同:

若要啟用偵錯模式,請在 android studio 控制台中使用下列命令:

adb shell setprop debug.firebase.analytics.app package_name

完成後,您可以測試並查看 Webview 事件的實作:

d230debf4ccfddad.png

6. 恭喜

恭喜,您已在 Android 應用程式中成功建立了 Web 視圖。您可以傳送和測量應用程式中透過網路視圖發生的關鍵漏斗事件。為了充分利用這一點,我們還建議連接到 Google Ads,並將這些事件作為轉換匯入。

你已經學會了

  • 如何將 Webview 事件傳送到 Firebase
  • 如何在 Android 中設定和建立簡單的 Webview

參考文檔