2016-12-19 221 views
1

的Android注入一個JS接口到Web查看通話的Android方法:從打字稿

JavaScriptInterface javaScriptInterface = new JavaScriptInterface(this); 
browser.addJavascriptInterface(javaScriptInterface, "qp"); 

界面看起來是這樣的:

public class JavaScriptInterface { 

    private ILoadEpi iLoadEpi; 

    public JavaScriptInterface(ILoadEpi iLoadEpi) { 
     this.iLoadEpi = iLoadEpi; 
    } 

    @JavascriptInterface 
    public void passParameters(String fldMerchCode, 
           String fldMerchRefNbr, 
           String fldTxnAmt, 
           String fldTxnScAmt, 
           String fldDatTimeTxn, 
           String fldDate1, 
           String fldDate2 
           ) { 
     Log.d("fldMerchCode", fldMerchCode); 
     Log.d("fldMerchRefNbr", fldMerchRefNbr); 
     Log.d("fldTxnAmt", fldTxnAmt); 
     Log.d("fldTxnScAmt", fldTxnScAmt); 
     Log.d("fldDatTimeTxn", fldDatTimeTxn); 
     Log.d("fldDate1", fldDate1); 
     Log.d("fldDate2", fldDate2); 
     iLoadEpi.loadEpi(fldMerchCode, fldMerchRefNbr, fldTxnAmt, fldTxnScAmt, fldDatTimeTxn, fldDate1, fldDate2); 
    } 
} 

怎麼能一個Web應用程序開發使用打字稿調用這個Android?

或者更廣泛地說,TypeScript應用程序如何調用Android方法?

回答

1

爲將由Android注入的JavaScriptInterface類型添加TypeScript定義。然後用Android注入的實例名稱聲明一個變量,然後按正常方式使用它。在你的榜樣,你需要的定義是:

interface JavaScriptInterface { 
    passParameters(fldMerchCode: string, 
        fldMerchRefNbr: string, 
        fldTxnAmt: string, 
        fldTxnScAmt: string, 
        fldDatTimeTxn: string, 
        fldDate1: string, 
        fldDate2: string) : void; 
} 

declare var qp: JavaScriptInterface; 

qp例如由Android注入將對它提供的方法passParameters。該實例由Android在browser.addJavaScriptInterface(javaScriptInterface, "qp");的調用中創建,名稱爲qp。請注意,根據passParameters函數的使用方式,您可能需要聲明返回類型爲any,而不是void

這裏的基礎上,Android guide for binding JS一個完整的例子:

在你的HTML文件,添加:

<input type="button" value="Say hello" id ="button"/> 
<script src="./generated/bundle.js"></script> 

,我假設你產生transpiled的JavaScript位於./generated/bundle.js /,相對於HTML文件。

在您的打字稿文件,添加:

interface WebAppInterface { 
    showToast(toast: string) : any; 
} 

declare var android: WebAppInterface; 

var button = document.getElementById('button'); 
button.onclick =()=>android.showToast('Hello Android!'); 

注意,鏈接Android的例子名被注入的對象android

webView.addJavascriptInterface(new WebAppInterface(this), "android"); 

而如果鏈接的示範性變化或消失,這裏是示例WebAppInterface.java:

public class WebAppInterface { 
    Context mContext; 

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

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