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

Android利用WebView开发Web App

2012-04-20 16:48 323 查看

步骤

1. 初始化。
WebView myWebView=
(WebView) findViewById(R.id.webview);

myWebView.loadUrl("http://www.example.com");

2. 设置支持javascript,默认为不可用。
WebSettings webSettings= myWebView.getSettings();

webSettings.setJavaScriptEnabled(true);

3 javascript访问android应用中方法。
webView.addJavascriptInterface(newJavaScriptInterface(this),"Android");

publicclass
JavaScriptInterface{

Context mContext;

/** Instantiate the interface and set the context */

JavaScriptInterface(Context c){

mContext = c;

}

/** Show a toast from the web page */

publicvoid showToast(String
toast){

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

}

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

<scripttype="text/javascript">

function showAndroidToast(toast){

Android.showToast(toast);

}

</script>

4 处理页面跳转。
myWebView.
setWebViewClient
(newMyWebViewClient());

privateclass
MyWebViewClientextends
WebViewClient{

@Override

public boolean
shouldOverrideUrlLoading
(WebView
view, String url){

if(Uri.parse(url).getHost().equals("www.example.com")){

// This is my web site, so do not override; let my WebView load the page

returnfalse;

}

// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs

Intent intent=
new Intent(Intent.ACTION_VIEW,Uri.parse(url));

startActivity(intent);

returntrue;

}

}

5 访问历史(返回,前进)。
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.
canGoBack
(){

myWebView.
goBack
();

returntrue;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: