1. 簡介
上次更新時間:2022 年 2 月 3 日
課程內容
- 如何在 Android 中建立非常簡單的 WebView
- 如何將 WebView 事件傳送至 Firebase
軟硬體需求
- 已導入 Analytics SDK 的 Firebase 專案
- Android Studio 4.2 以上版本。
- 搭載 Android 5.0 以上版本的 Android Emulator。
- 熟悉 Java 程式設計語言。
- 熟悉 JavaScript 程式設計語言。
2. 在 Android 中建立簡易 WebView
在活動版面配置中新增 WebView
如要在版面配置中將 WebView 新增至應用程式,請將下列程式碼加入活動的版面配置 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 權限。例如:
<uses-permission android:name="android.permission.INTERNET" />
這就是顯示網頁的基本 WebView 所需的一切。
在 WebView 中使用 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");
}
}
3. 實作 JavaScript 橋接介面
Javacript 處理常式
如要在 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 非常簡單,它有三個按鈕,用來記錄事件,另一個則用來記錄使用者屬性:
按一下按鈕後,就會命名為「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 事件如何生效:
6. 恭喜
恭喜!您已成功在 Android 應用程式中建立 WebView。您可以透過 WebView,傳送及評估應用程式內發生的重要事件。為充分發揮這項功能的效益,我們也建議您連結至 Google Ads,將這些事件匯入為轉換。
您已學習以下內容
- 如何將 Webview 事件傳送至 Firebase
- 如何在 Android 中設定及建立簡易 WebView