If your app is in hybrid mode and needs to call an HTML5 page to report data through JavaScript, the method of calling the HMS Core Analytics SDK in the HTML5 page must be forwarded by the native code of the app to the JavaScript. The sample code is as follows:
- // 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 jsonString){
- //
- }
- }
- // Add the HiAnalyticsWebInterface instance to the JavaScript API of the webView.
- public class WebActivity extends AppCompatActivity{
- WebView webView;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- webView=new WebView(this);
- //...
- // Define the JavaScript object exposed to the HTML5 page as HiAnalyticsObj.
- webView.addJavascriptInterface(new HiAnalyticsWebInterface(this),"HiAnalyticsObj");
- }
- }
- // The onEvent method is used as an example. The access methods of other methods are similar.
- function onEvent(eventName,eventParams){
- if(!eventName){
- return
- }
- if(window.HiAnalyticsObj){
- window.HiAnalyticsObj.onEvent(eventName,JSON.stringify(eventParams))
- }else{
- console.log('no method found')
- }
- }