2013-05-01 41 views
2

我有一個問題。一個HTML5頁面可以與android中的本地組件進行交互嗎?HTML5可以訪問本機組件

我想要實現的是在顯示內容列表的HTML5頁面上。我想創建一些內容已經到達的通知。?

進出口猜測,一種方法是使用webview並顯示我的HTML5內容,但如何從webview獲取回調,以便我可以通知用戶某些內容已通過通知欄到達,可以是使用原生android編碼進行訪問?

我已經知道如何在android上創建通知以及如何創建webview,我只需要找到一種方法將數據從html5頁面發送到android組件,反之亦然。

這是可以實現的還是太過雄心勃勃?

回答

3

是的,你可以通過JavaScript接口來實現。通過這個JavaScript可以調用您附加的界面中定義的函數。

http://developer.android.com/guide/webapps/webview.html

在你Activity

WebAppInterface mInterface; 

public void onCreate() { 
    mInterface = new WebAppInterface(this); 
    mWebView.addJavascriptInterface(mInterface, "MyAndroidInterface") 
} 

現在定義的對象,其中的來電會轉到:

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(); 
    } 
} 

現在Javascript你可以這樣做:

MyAndroidInterface.showToast("hello world"); 

回來的路上(從nativeJavascript)你可以通過Javascript injection。 在Javascript定義功能:

function helloBack(param) { 
} 

現在,您可以撥打mWebView.loadUrl("javascript:helloBack(hi);");

+0

優秀。只是我在找什麼。有了這個我可以發送Intents,訪問服務等使用這個接口? – jonney 2013-05-01 14:43:14

+0

是的,請確保您的組件具有意圖發送所需的上下文。 – RvdK 2013-05-01 14:53:47

相關問題