Android app打开H5页一般要实现如下需求:
1、打开指定url网页;
2、点击链接可以跳转到下一页,并更新标题;
3、按back键或左箭头可以返回上一页;
4、当webview显示的是第一级url时, 按返回键或左箭头关闭当前界面;
5、WebView如何传值给Android, 例如使用H5登录成功后返回姓名、token等等字段。
6、支持JavaScript, 支持显示JS对话框。
7、无网络时显示默认布局, 以提高用户体验。
8、避免WebView的内存泄漏。
不多说, 看下面代码如何实现上述功能。
参考布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:my="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/activity_main_bg"
android:orientation="vertical">
<com.eloancn.borrower.common.widget.TitleView
android:id="@+id/titleView"
android:layout_width="match_parent"
android:layout_height="50dp"
my:titleText="H5" />
<RelativeLayout
android:id="@+id/rl_webViewContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!--在代码中添加webView防止内存泄露隐患-->
<LinearLayout
android:id="@+id/neterror_tip"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:visibility="gone">
<ImageView
android:layout_marginTop="110dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/not_found" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
示例代码:
public class CommonWebViewActivity extends Activity {
private WebView mWebView;
private TitleView mTitleView;
private RelativeLayout mWebViewContainer;
private String title;
private String url;
private LinearLayout neterrorLayout;
private int mFlag; //来源
public static final int FLAG_SIGNATURE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_common_webview_main);
initData();
initView();
setData();
}
@Override
protected void onDestroy() {
super.onDestroy();
mWebView.setWebViewClient(null);
mWebView.setWebChromeClient(null);
mWebViewContainer.removeView(mWebView);
mWebView.removeAllViews();
mWebView.destroy();
}
private void initData() {
url = getIntent().getStringExtra("url");
title = getIntent().getStringExtra("title");
mFlag = getIntent().getIntExtra("flag", 0);
}
private void initView() {
mTitleView = (TitleView) findViewById(R.id.titleView);
mWebViewContainer = (RelativeLayout) findViewById(R.id.rl_webViewContainer);
neterrorLayout = (LinearLayout) findViewById(R.id.neterror_tip);
mWebView = new WebView(getApplicationContext());
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
mWebViewContainer.addView(mWebView, layoutParams);
WebSettings webSettings = mWebView.getSettings();
//设置WebView属性,能够执行Javascript脚本
webSettings.setJavaScriptEnabled(true);
//设置可以访问文件
webSettings.setAllowFileAccess(true);
//设置支持缩放
webSettings.setBuiltInZoomControls(false);
//允许js弹出窗口
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
mTitleView.setLeftBtnClickListener(new TitleView.OnBtnClickListener() {
@Override
public void onClick(View v) {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
finish();
}
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private void setData() {
mTitleView.setTitle(title);
mWebView.loadUrl(url);
mWebView.setWebChromeClient(new WebChromeClient(){
@Override
public boolean onJsAlert(WebView view, String url, final String message, final JsResult result) {
//注意,WebView默认不会显示JavaScript的Alert,需要Android实现。
runOnUiThread(new Runnable() {
@Override
public void run() {
//自定义美观的Dialog,仅仅是为了显示message
CustomDialog.Builder builder = new CustomDialog.Builder(CommonWebViewActivity.this);
builder.setTitle("提示");
builder.setMessage(message);
builder.setSingle("知道了", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.create().show();
}
});
result.confirm();//这里必须调用,否则页面会阻塞造成假死
return true;
}
@Override
public void onReceivedTitle(final WebView view, final String title) {
super.onReceivedTitle(view, title);
if (FLAG_SIGNATURE == mFlag) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mTitleView.setTitle(title);
}
});
}
}
});
mWebView.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
if (FLAG_SIGNATURE == mFlag) {
Log.d("brycegao", "shouldInterceptRequest url:" + request.getUrl().toString());
if (request.getUrl().toString().contains("wxd://getImage?tenderid=")) {
//可以通过url传值给Android, 即在url里放置想要的参数
runOnUiThread(new Runnable() {
@Override
public void run() {
setResult(RESULT_OK);
finish();
}
});
}
}
return super.shouldInterceptRequest(view, request);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
mWebView.loadUrl(url);
return true;
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
if (FLAG_SIGNATURE == mFlag
&& request.getUrl().toString().contains("wxd://getImage?tenderid=")) {
//do nothing
mWebView.setVisibility(View.GONE); //优化体验,避免显示错误信息
} else {
//加载失败
neterrorLayout.setVisibility(View.VISIBLE);
mWebView.setVisibility(View.GONE);
}
}
});
neterrorLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mWebView.setVisibility(View.VISIBLE);
neterrorLayout.setVisibility(View.GONE);
mWebView.loadUrl(url);
}
});
}
}