欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android WebView的使用方法总结

程序员文章站 2022-05-28 10:21:56
 android webview的使用方法   android app打开h5页一般要实现如下需求: 1、打开指定url网页; 2、点击链接可...

 android webview的使用方法

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


以上就是android webview的使用方法详解,大家如果有疑问可以留言讨论,或者到本站社区交流,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!