目录

Calling Device APIs on an HTML5 Page Using JavaScript in Hybrid Mode

If your app uses the Hybrid mode and needs to call an HTML5 page to report data through JavaScript, the method of calling the Analytics SDK on the HTML5 page must be forwarded by the native code of the app to the JavaScript. The sample code is as follows:

Methods Exposed to the WebView in the App

// Define the JavaScript object exposed to an HTML5 page. The methods marked with JavascriptInterface can be called by the HTML5 page.
public class HiAnalyticsWebInterface{
   HiAnalyticsInstance instance;
   public HiAnalyticsWebInterface(Context context){
       HiAnalyticsTools.enableLog();
       instance = HiAnalytics.getInstance(context);
       instance.setAnalyticsEnabled(true);
   }
   @JavascriptInterface
   public void onEvent(String eventName,String jsonString) {
       instance.onEvent(eventName,bundleFromJson(jsonString));
   }
   private Bundle bundleFromJson(String parameters){
    // Convert the character string into a Bundle object.
   }
}
// Add the HiAnalyticsWebInterface instance to the JavaScript API of WebView.
public class WebActivity extends AppCompatActivity {
    WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        webView = new WebView(this);
        // ...
        // Define the JavaScript object exposed to the HTML5 page as HiAnalyticsObj.
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new HiAnalyticsWebInterface(this), "HiAnalyticsObj");
    }
}

Sample Code for Calling a Method on an HTML5 Page

// The onEvent method is used as an example. Other methods can be called in a similar way.
function onEvent(eventName,eventParams){
   if(!eventName){
     return
   }
   if(window.HiAnalyticsObj){
       window.HiAnalyticsObj.onEvent(eventName,JSON.stringify(eventParams))
   }else{
       console.log('no method found')
   }
}