2017-07-27 55 views
1

我正在構建一個android應用程序,其中在webView上加載失敗HTTP文件,該文件位於assets文件夾中。以下是失敗HTTP文件的代碼。如何在javascript中調用接口並調用android方法?

<html> 
<head> 
</head> 
<body> 
<a href="javascript:void(0);" onclick="init();">Click on this link for a log 
message</a> 
<br><br><br><br><br> 

<script> 
function init(){ 
    android.log('Data from JS'); 
    android.log(android.data); 
} 

function showMessage(str){ 
    android.log(str); 
} 
</script> 

</body> 
</html> 

的OnCreate代碼

//add interface 
    wv.addJavascriptInterface(jsInterface, "android");//android is the 
    keyword that will be exposed in js 

OnClick方法和接口方法

public void click(View view){ 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 
     wv.evaluateJavascript("javascript:showMessage('Hello World!')", null); 
    } 
} 

//javascript interface 
private class JsInterface { 
    @JavascriptInterface 
    //function that will be called from assets/test.js 
    //js example: android.log('my message'); 
    public String data() { 
     return "DATA FROM ANDROID"; 
    } 

    public void log(String msg) { 
     Log.d("MSG FROM JAVASCRIPT", msg); 
    } 
} 

以上是完整的代碼,我如何使用接口在JavaScript中。我已經使用了相同的工作在我的舊項目,但現在不工作可以任何人回答我是這種方法已被棄用在Android或有任何其他的解決這個?

回答

0

這是JS接口類:

public class JS_INTERFACE { 

    Context mContext; 

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

    /** Show a toast from the web page */ 
    @JavascriptInterface 
    public void native_showToast(String toast) { 
     Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); 
    } 

    @JavascriptInterface 
    public void native_ShowNotifyTest1(String toast , String BigOrSmall) { 

     Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); 

    } 

} 


@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

    WebSettings settings = webView1.getSettings(); 

    // Enable Javascript 
    settings.setJavaScriptEnabled(true); 

    webView1.addJavascriptInterface(new JS_INTERFACE(getContext()), "android"); 

} 

我用onCreateView init的。

更新答案:

使用JQ在您的應用程序(使用簡單evaluateJavascript):

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { 

     webView.evaluateJavascript("someJQFunction();", null); 

    } 
else { 

     webView.loadUrl("javascript: someJQFunction();"); 

    } 
+0

感謝你能告訴我如何添加jQuery的android系統 –