您的位置:首页 > 移动开发 > Android开发

Android项目中的assert文件下的html里的js交互

2014-03-24 15:39 330 查看
要是webview能够与JavaScript交互,首先需要webview要启用JavaScript:

WebSettings webSettings = myWebView.getSettings();  

        webSettings.setJavaScriptEnabled(true);  
 然后创建JavaScript的接口:

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

        }  

    }  

给webview添加JavaScript接口:

[html] view
plaincopy

myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");  

  本地JavaScript文件:

[javascript] view
plaincopy

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />  

  

<script type="text/javascript">  

    function showAndroidToast(toast) {  

        Android.showToast(toast);  

    }  

</script>  

  整个代码如下:

[java] view
plaincopy

public class MainActivity extends Activity {  

    private WebView myWebView;  

  

    @Override  

    protected void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.activity_main);  

        myWebView = (WebView) findViewById(R.id.webview);  

        WebSettings webSettings = myWebView.getSettings();  

        webSettings.setJavaScriptEnabled(true);  

        myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");  

        ProcessWebString();  

  

    }  

  

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

        }  

    }  

  

    private void ProcessWebString() {  

        // 加载 asset 文件  

        String tpl = getFromAssets("web_tpl.html");  

        myWebView.loadDataWithBaseURL(null, tpl, "text/html", "utf-8", null);  

    }  

  

    /* 

     * 获取html文件 

     */  

    public String getFromAssets(String fileName) {  

        try {  

            InputStreamReader inputReader = new InputStreamReader(  

                    getResources().getAssets().open(fileName));  

            BufferedReader bufReader = new BufferedReader(inputReader);  

            String line = "";  

            String Result = "";  

            while ((line = bufReader.readLine()) != null)  

                Result += line;  

            return Result;  

        } catch (Exception e) {  

            e.printStackTrace();  

        }  

        return "";  

    }  

  

}  

这里获取到的是assert文件下的html字符串,写了一个方法获取assert文件下html

还有种方法可以直接load

webView.loadUrl("file:///android_asset/html/company.html");

assets文件下的html文件下的company.html文件

webView.setWebChromeClient(new MyWebClient());

private class MyWebClient extends WebChromeClient {

@Override
public boolean onJsAlert(WebView view, String url, String message,
JsResult result) {
// TODO Auto-generated method stub
Intent intent = null;
if (message.contains("tid")) {
Pattern pattern = Pattern.compile("tid=(\\d+)");
Matcher matcher = pattern.matcher(message);
String tid = "";
while (matcher.find()) {
String st = matcher.group(0);
tid = st.split("=")[1];
System.out.println("---" + tid);
}
intent = new Intent(BbsMyHomeActivity.this,
BbsHomeDetailTestActivity.class);
intent.putExtra("tid", tid);
} else {
intent = new Intent(BbsMyHomeActivity.this,
MyAttentionDetailActivity.class);
intent.putExtra("uid", message);
}
startActivity(intent);

// new CustomeToast(BbsMyHomeActivity.this, message);
new PopupToast(BbsMyHomeActivity.this, message, footlayout);
// 少写了这行代码可能会导致,点击了一次js里的alert弹出方法,无法点击第二次。
result.cancel();
return true;
}
}
http://blog.csdn.net/ithomer/article/details/8737999
做项目的时候还发现一个问题,就是WebView的addJavascriptInterface方法失效的问题

里面的类的方法名上面要加annotation
@JavascriptInterface


表忘了导包import
android.webkit.JavascriptInterface;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: