androidandroid-webviewandroid-websettings

I can't use Intent at Activity


when I click the marker on Google Map, I want it to enter another Activity, but when I got the result from javascript, it can't do Intent

WebSettings webSetting = webView.getSettings();
webSetting.setJavaScriptEnabled(true);
webSetting.setDisplayZoomControls(true);
webSetting.setSupportZoom(true);
webSetting.setBuiltInZoomControls(true);
webView.addJavascriptInterface(new JavaScriptInterfaceTest(this), "Android");

and my JavaScriptInterfaceTest():

public class JavaScriptInterfaceTest {
  Context mContext;

  /** Instantiate the interface and set the context */
  JavaScriptInterfaceTest(Context c) {
    mContext = c;
  }

  /** Show a toast from the web page */
  @JavascriptInterface
  public void responseResult(String result){
    Log.e("JsCallBack","DRINK");
    Intent mainIntent = new Intent(MainActivity.this, Test.class);
    startActivity(mainIntent);
  }

  @JavascriptInterface
  private void startActivity(Intent mainIntent) {
    // TODO Auto-generated method stub
  }
}

HTML:

drinkMarker = new google.maps.Marker({
                   position: {lat: 25.079734,lng: 121.569519},
                   map: map,
                   });
drinkMarker.addListener('click',function(){
                        Android.responseResult("drink");
                        });

Solution

  • Pass the Current context instead of MainActivity

    public class JavaScriptInterfaceTest {
      Context mContext;
    
      /** Instantiate the interface and set the context */
      JavaScriptInterfaceTest(Context c) {
        mContext = c;
      }
    
      /** Show a toast from the web page */
      @JavascriptInterface
      public void responseResult(String result){
        Log.e("JsCallBack","DRINK");
        Intent mainIntent = new Intent(mContext, Test.class);
         mContext.startActivity(mainIntent);
      }
    
      @JavascriptInterface
      private void startActivity(Intent mainIntent) {
        // TODO Auto-generated method stub
      }
    }