Android中Webview使用自訂的javascript進行回調

來源:互聯網
上載者:User

 

先說為什麼需要討論這個問題。

 

現在很多的手機應用,都可能會直接嵌入一個web頁面。這樣做的好處:一個是功能更新方便,維護起來容易,只需要維護伺服器的頁面即可,不需要更新用戶端;另一個是功能通用,不僅android可以用,ios也可以用,symbian也可以直接用。

 

那為什麼現在很多手機應用並不做成web方式的呢?原因很多。一個是現階段web方式展現能力相對較弱,如果對於應用的美觀程度要求比較高,就無法使用web方式;一個是web方式速度相對較慢,使用者體驗會受一些影響;一個是現階段流量還是相對寶貴,web方式流量相對較大;還有一個就是有一些功能無法使用web方式實現(關於這一點,現在又很多開源的項目可以實現手機的一些硬體功能,比如拍照啊,擷取通訊錄啊,都是可以的,感興趣的可以搜尋一下phoneGap。但是從現有的反饋來看,速度較慢,體驗較差)。

 

基於以上的原因,現在很多項目會把一部分功能做成web方式的,一部分功能用其它控制項來寫。這就需要web頁面與其它控制項做一些互動。如何互動呢,就是利用自訂的javascript。

 

下面虛擬一個情境。

 

現在有一個功能,展現目前使用者的好友名單,好友名單頁是web方式的,點擊某好友的頭像以後,進入該好友的詳情頁面,而這個頁面呢,由於某些原因,沒做成web方式的。

 

假設好友名單頁是UserListActivity,包含一個webview。好友詳情頁面是UserDetailActivity,包含很多控制項和商務邏輯。

 

我們以id來唯一標示使用者。好友名單頁中,點擊每一個好友頭像,都會調用:

onclick="javascript:android.user('1')"

類似這樣的js語句。因本文主要介紹android,而不是web開發內容,所以具體不再詳述,熟悉web開發的同學很容易理解。

 

我們現在需要做的,就是顯示使用者列表頁面,然後在使用者點擊頭像以後,響應具體的js請求,跳到該好友詳細頁面。

 

下面看看大概的實現方法。

 

預設情況下,在WebView中是不能使用javascript的。可以通過下面的代碼:

WebView myWebView = (WebView) findViewById(R.id.webview);WebSettings webSettings = myWebView.getSettings();webSettings.setJavaScriptEnabled(true);

 

使javascript功能可用。這部分代碼都放在UserListActivity中的onCreate()方法裡。

 

然後是註冊JS介面。先看看webview的一個方法。

 

public void addJavascriptInterface (Object obj, String interfaceName)

Since: API Level 1

Use this function to bind an object to JavaScript so that the methods can be accessed from JavaScript.

IMPORTANT:

·         Using addJavascriptInterface() allows JavaScript to control your application. This can be a very useful feature or a dangerous security issue. When the HTML in the WebView is untrustworthy (for example, part or all of the HTML is provided
by some person or process), then an attacker could inject HTML that will execute your code and possibly any code of the attacker's choosing.
Do not use addJavascriptInterface() unless all of the HTML in this WebView was written by you.

·         The Java object that is bound runs in another thread and not in the thread that it was constructed in.

Parameters

obj

The class instance to bind to JavaScript, null instances are ignored.

interfaceName

The name to used to expose the instance in JavaScript.

 

我們在UserListActivity類的onCreate()方法中增加如下語句:

mWebView.addJavascriptInterface(this, "android");

在UserListActivity類中增加如下方法:

public void user(String id) {

        // 擷取id,跳轉activity。

    }

 

這樣當頁面調用onclick="javascript:android.user('1')"語句的時候,就可以映射到UserListActivity對象的user()方法了。

這裡user方法有一個參數,是要對應js語句的user(‘1’)。

 

下面附上所有代碼。

 

Android部分的代碼:

 

package com.arui.framework.android.js; import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.webkit.WebSettings;import android.webkit.WebView; import com.arui.framework.R;import com.arui.framework.android.js.UserDetailActivity; public class UserListActivity extends Activity {     private WebView mWebView;        @Override    public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);              setContentView(R.id.userlist);              mWebView = (WebView) findViewById(R.id.mywebview);       WebSettings webSetting = mWebView.getSettings();       //設定js可用       webSetting.setJavaScriptEnabled(true);       // 添加js調用介面       mWebView.addJavascriptInterface(this, "android");        //載入具體的web地址       mWebView.loadUrl("http://blog.csdn.net/arui319");       mWebView.setVisibility(View.VISIBLE);       mWebView.requestFocus();    }        public void user(String id) {        //跳轉activity       Intent intent = new Intent(this, UserDetailActivity.class);       intent.putExtra("id", id);       startActivity(intent);    } }

 

資源檔:

<?xml version="1.0" encoding="utf-8"?><LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent" >    <WebView       android:id="@+id/mywebview"       android:layout_width="fill_parent"       android:layout_height="fill_parent"        android:visibility="gone"/></LinearLayout>

 

Web頁面的局部代碼:

<img src="……" onclick="javascript:android.user('1')" />

 

---------------------------------------------------------------------------

GL(arui319)

http://blog.csdn.net/arui319

<本文可以轉載,但是請保留以上作者資訊。謝謝。>

---------------------------------------------------------------------------

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.