001package de.econda.droid.hybrid; 002 003import android.os.Build; 004import android.util.Log; 005import android.webkit.JavascriptInterface; 006import android.webkit.WebView; 007 008import org.json.JSONObject; 009 010import de.econda.droid.PageView; 011import de.econda.droid.Session; 012import de.econda.droid.impl.Constants; 013 014 015/** 016 * A JavascriptInterface for using from inside a WebView via the outside Android-SDK-API. 017 * 018 * @see <a href="https://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)" target="_blank">WebView.addJavascriptInterface</a> 019 */ 020public class AndroidEmos { 021 private final Session session; 022 023 024 public AndroidEmos(Session session) { 025 this.session = session; 026 } 027 028 /** 029 * Called from inside webview by Javascript 030 * 031 * Since WebView JavascriptInterface can only handle simple Parameters as String or int, 032 * there is nor possibility to use a JSONObject as Object. 033 * You must serialize in Browser to String, deserialization is then done i this Method. 034 * 035 * Afterwards jsonData is send via the Session-Object vom Android-SDK-API as all other Android-Analytics-Data. 036 * (with same shared Session and Visitor Information) 037 * 038 * @param jsonObjectAsString json serialized as String 039 */ 040 @JavascriptInterface 041 public void send(String jsonObjectAsString){ 042 043 try { 044 JSONObject properties = new JSONObject(jsonObjectAsString); 045 046 session.addPageView(new PageView(properties)); 047 048 } catch (Exception ex) { 049 Log.i(Constants.LOG_TAG, "Deserialization Problem? jsonObjectAsString=" + jsonObjectAsString, ex); 050 } 051 } 052 053 054 /** 055 * Adding the AndroidEmos JavascriptInterface to WebView, 056 * callable from Javascript in WebView with name "androidEmos". 057 * 058 * Due to Security Concerns, this should not be used for Android versions before Jelly Bean (API Version 17) 059 * 060 * @see <a href="https://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)" target="_blank">WebView.addJavascriptInterface</a> 061 * 062 * @param webView The webView to witch the Interface should be addded 063 * @param session The Session 064 * @param onlyIfSecure Weather method should be executed only with Android Version newer than Jelly Bean (Android Version 17) 065 * 066 * 067 */ 068 public static void addJavascriptInterfaceToWebView(WebView webView, Session session, boolean onlyIfSecure) { 069 070 if (onlyIfSecure && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { 071 Log.w(Constants.LOG_TAG, "Not adding JavaScriptInterface, API Version: " + Build.VERSION.SDK_INT); 072 } else { 073 webView.addJavascriptInterface(new AndroidEmos(session), "androidEmos"); 074 } 075 } 076}