1. In order to establish communication between the web view(HTML) and the native code, we use the native javascript interface.

  2. This way you can pass the event information from the WebView to the native code. Once the data received in the interface method, it will be sent to the backend through the datagran_android_sdk.

  3. In order to pass the data from the HTML to native, you can integrate the pixel javascript SDK which will handle it.

  4. Integrate the following Javascript interface Class in the application.

    public class DatagranWebInterface {
        private Context mContext;
    
        /**
         * Instantiate the interface and set the context
         */
        public DatagranWebInterface(Context c) {
            this.mContext = c;
        }
    
        @JavascriptInterface
        public void identify(String userId) {
            if(!userId.isEmpty()) {
                Tracker.singleton().identify(userId, mContext, false);
            }
        }
    
        @JavascriptInterface
        public void reset() {
            Tracker.singleton().resetDGuserid();
        }
    
        @JavascriptInterface
        public void trackCustom(String name, String args) throws JSONException {
            JSONObject json = new JSONObject(args);
            if(json != null && json.length() >= 1) {
                Gson gson = new Gson();
                JsonElement jsonElement = gson.fromJson(json.toString(), JsonElement.class);
                JsonObject payload = gson.fromJson((gson.toJson(jsonElement)), JsonObject.class);
                Tracker.singleton().trackCustom(name, payload, mContext, false);
            } else {
                Log.e("DG","Empty Json");
            }
    
        }
    
    }
    
    
  5. Example WebViewActivity

    public class WebViewActivity extends Activity {
    
        private WebView webView = null;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_webview);
            webView = findViewById(R.id.webview);
    
            DatagranWebInterface jsInterface = new DatagranWebInterface(getApplicationContext());
            webView.addJavascriptInterface(jsInterface, "DatagranWebInterface");
    
            WebSettings mWebSettings = webView.getSettings();
            mWebSettings.setJavaScriptEnabled(true);
    
            webView.loadUrl("<https://app.datagran.io>");
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }
            });
    
        }
    }