简体   繁体   中英

Unable to call my Java class from Javascript In my Android App

i don't Know whats wrong with the code below am trying to call my java class from javascript code using the webview addJavainterface but seems not to be working, i try to follow the tutorial on android website but still no luck help i dont actually know what am missing.. here is my code...My JavaScript code is like this:

public class HomeFragment extends Fragment {
 private WebView webView;
 private Bundle webViewBundlehome;  

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {        
    View rootView = inflater.inflate(R.layout.home_layout, container, false);
    webView =(WebView) rootView.findViewById(R.id.webViewHome);
    WebSettings websettings = webView.getSettings(); 
    websettings.setJavaScriptEnabled(true);
    websettings.setDomStorageEnabled(true);
    webView.addJavascriptInterface(new JavaScriptInterface(),"Android");

    if(webViewBundlehome==null){
        webView.loadUrl("file:///android_asset/www/index.html");

    }
    else
    {

        webView.restoreState(webViewBundlehome);        
    }

    return rootView;
}


@Override
public void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    webViewBundlehome = new Bundle();
    webView.saveState(webViewBundlehome);
}


public class JavaScriptInterface {
    private Activity activity;      
    public void opencart(String cart_id){
        Intent intent = new Intent(activity, Cartegory.class);
        intent.putExtra("cart_id", cart_id);
        startActivity(intent);          
    }

    public void openproduct(String pro_id){
        Intent intent = new Intent(activity,view.class);
        intent.putExtra("pro_id", pro_id);
        startActivity(intent);
    }

}}



$('#mybutton').on("click",function(){
Android.openproduct(product_id);
})


android:targetSdkVersion="19" 

Since you're targeting API 19 you'll need to decorate the opencart and openproduct java methods with @JavascriptInterface . See here for details.
But it looks something like

class JsObject {
    @JavascriptInterface
    public String toString() { return "injectedObject"; }
}

I'd also do something simple (such as a log message) to make sure that the javascript call is working correctly; then update to starting activities.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM