当前位置: 首页 > 软件库 > 手机/移动开发 > >

Android-AdvancedWebView

授权协议 MIT License
开发语言 Java
所属分类 手机/移动开发
软件类型 开源软件
地区 不详
投 递 者 白祺然
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

AdvancedWebView

Enhanced WebView component for Android that works as intended out of the box

Requirements

  • Android 2.2+

Installation

  • Add this library to your project
    • Declare the Gradle repository in your root build.gradle

      allprojects {
          repositories {
              maven { url "https://jitpack.io" }
          }
      }
    • Declare the Gradle dependency in your app module's build.gradle

      dependencies {
          implementation 'com.github.delight-im:Android-AdvancedWebView:v3.2.1'
      }

Usage

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

Layout (XML)

<im.delight.android.webview.AdvancedWebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Activity (Java)

Without Fragments

public class MyActivity extends Activity implements AdvancedWebView.Listener {

    private AdvancedWebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        mWebView = (AdvancedWebView) findViewById(R.id.webview);
        mWebView.setListener(this, this);
        mWebView.setMixedContentAllowed(false);
        mWebView.loadUrl("http://www.example.org/");

        // ...
    }

    @SuppressLint("NewApi")
    @Override
    protected void onResume() {
        super.onResume();
        mWebView.onResume();
        // ...
    }

    @SuppressLint("NewApi")
    @Override
    protected void onPause() {
        mWebView.onPause();
        // ...
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mWebView.onDestroy();
        // ...
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        mWebView.onActivityResult(requestCode, resultCode, intent);
        // ...
    }

    @Override
    public void onBackPressed() {
        if (!mWebView.onBackPressed()) { return; }
        // ...
        super.onBackPressed();
    }

    @Override
    public void onPageStarted(String url, Bitmap favicon) { }

    @Override
    public void onPageFinished(String url) { }

    @Override
    public void onPageError(int errorCode, String description, String failingUrl) { }

    @Override
    public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) { }

    @Override
    public void onExternalPageRequest(String url) { }

}

With Fragments (android.app.Fragment)

Note: If you're using the Fragment class from the support library (android.support.v4.app.Fragment), please refer to the next section (see below) instead of this one.

public class MyFragment extends Fragment implements AdvancedWebView.Listener {

    private AdvancedWebView mWebView;

    public MyFragment() { }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_my, container, false);

        mWebView = (AdvancedWebView) rootView.findViewById(R.id.webview);
        mWebView.setListener(this, this);
        mWebView.setMixedContentAllowed(false);
        mWebView.loadUrl("http://www.example.org/");

        // ...

        return rootView;
    }

    @SuppressLint("NewApi")
    @Override
    public void onResume() {
        super.onResume();
        mWebView.onResume();
        // ...
    }

    @SuppressLint("NewApi")
    @Override
    public void onPause() {
        mWebView.onPause();
        // ...
        super.onPause();
    }

    @Override
    public void onDestroy() {
        mWebView.onDestroy();
        // ...
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        mWebView.onActivityResult(requestCode, resultCode, intent);
        // ...
    }

    @Override
    public void onPageStarted(String url, Bitmap favicon) { }

    @Override
    public void onPageFinished(String url) { }

    @Override
    public void onPageError(int errorCode, String description, String failingUrl) { }

    @Override
    public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) { }

    @Override
    public void onExternalPageRequest(String url) { }

}

With Fragments from the support library (android.support.v4.app.Fragment)

  • Use the code for normal Fragment usage as shown above

  • Change

    mWebView.setListener(this, this);

    to

    mWebView.setListener(getActivity(), this);
  • Add the following code to the parent FragmentActivity in order to forward the results from the FragmentActivity to the appropriate Fragment instance

    public class MyActivity extends FragmentActivity implements AdvancedWebView.Listener {
    
     @Override
     public void onActivityResult(int requestCode, int resultCode, Intent intent) {
         super.onActivityResult(requestCode, resultCode, intent);
         if (mFragment != null) {
             mFragment.onActivityResult(requestCode, resultCode, intent);
         }
     }
    
    }

ProGuard (if enabled)

-keep class * extends android.webkit.WebChromeClient { *; }
-dontwarn im.delight.android.webview.**

Cleartext (non-HTTPS) traffic

If you want to serve sites or just single resources over plain http instead of https, there’s usually nothing to do if you’re targeting Android 8.1 (API level 27) or earlier. On Android 9 (API level 28) and later, however, cleartext support is disabled by default. You may have to set android:usesCleartextTraffic="true" on the <application> element in AndroidManifest.xml or provide a custom network security configuration.

Features

  • Optimized for best performance and security

  • Features are patched across Android versions

  • File uploads are handled automatically (check availability with AdvancedWebView.isFileUploadAvailable())

    • Multiple file uploads via single input fields (multiple attribute in HTML) are supported on Android 5.0+. The application that is used to pick the files (i.e. usually a gallery or file manager app) must provide controls for selecting multiple files, which some apps don't.
  • JavaScript and WebStorage are enabled by default

  • Includes localizations for the 25 most widely spoken languages

  • Receive callbacks when pages start/finish loading or have errors

    @Override
    public void onPageStarted(String url, Bitmap favicon) {
        // a new page started loading
    }
    
    @Override
    public void onPageFinished(String url) {
        // the new page finished loading
    }
    
    @Override
    public void onPageError(int errorCode, String description, String failingUrl) {
        // the new page failed to load
    }
  • Downloads are handled automatically and can be listened to

    @Override
    public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
        // some file is available for download
        // either handle the download yourself or use the code below
    
        if (AdvancedWebView.handleDownload(this, url, suggestedFilename)) {
            // download successfully handled
        }
        else {
            // download couldn't be handled because user has disabled download manager app on the device
            // TODO show some notice to the user
        }
    }
  • Enable geolocation support (needs <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />)

    mWebView.setGeolocationEnabled(true);
  • Add custom HTTP headers in addition to the ones sent by the web browser implementation

    mWebView.addHttpHeader("X-Requested-With", "My wonderful app");
  • Define a custom set of permitted hostnames and receive callbacks for all other hostnames

    mWebView.addPermittedHostname("example.org");

    and

    @Override
    public void onExternalPageRequest(String url) {
        // the user tried to open a page from a non-permitted hostname
    }
  • Prevent caching of HTML pages

    boolean preventCaching = true;
    mWebView.loadUrl("http://www.example.org/", preventCaching);
  • Check for alternative browsers installed on the device

    if (AdvancedWebView.Browsers.hasAlternative(this)) {
        AdvancedWebView.Browsers.openUrl(this, "http://www.example.org/");
    }
  • Disable cookies

    // disable third-party cookies only
    mWebView.setThirdPartyCookiesEnabled(false);
    // or disable cookies in general
    mWebView.setCookiesEnabled(false);
  • Allow or disallow (both passive and active) mixed content (HTTP content being loaded inside HTTPS sites)

    mWebView.setMixedContentAllowed(true);
    // or
    mWebView.setMixedContentAllowed(false);
  • Switch between mobile and desktop mode

    mWebView.setDesktopMode(true);
    // or
    // mWebView.setDesktopMode(false);
  • Load HTML file from “assets” (e.g. at app/src/main/assets/html/index.html)

    mWebView.loadUrl("file:///android_asset/html/index.html");
  • Load HTML file from SD card

    // <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.loadUrl("file:///sdcard/Android/data/com.my.app/my_folder/index.html");
    }
  • Load HTML source text and display as page

    myWebView.loadHtml("<html>...</html>");
    
    // or
    
    final String myBaseUrl = "http://www.example.com/";
    myWebView.loadHtml("<html>...</html>", myBaseUrl);
  • Enable multi-window support

    myWebView.getSettings().setSupportMultipleWindows(true);
    // myWebView.getSettings().setJavaScriptEnabled(true);
    // myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    
    myWebView.setWebChromeClient(new WebChromeClient() {
    
        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            AdvancedWebView newWebView = new AdvancedWebView(MyNewActivity.this);
            // myParentLayout.addView(newWebView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(newWebView);
            resultMsg.sendToTarget();
    
            return true;
        }
    
    }

Contributing

All contributions are welcome! If you wish to contribute, please create an issue first so that your feature, problem or question can be discussed.

License

This project is licensed under the terms of the MIT License.

  •        在android开发工作中经常会遇到与附件相关的功能需求,有时候会遇到除了图片附件之外其他格式文件的处理需求。关于图片类型附件相关的处理(压缩,上传,下载)这里就不再累述。下面主要说下其他格式文件的处理。 一 PDF格式文件 展示:                 (1) https://github.com/JoanZapata/android-pdfview 此三方控件只支持项目

  • 在运行android项目时,总是报错,提示:Android ERROR: Failed to resolve: com.github.**** 我原来的build.gradle文件: // Top-level build file where you can add configuration options common to all sub-projects/modules. buildsc

  • 针对Webview 支持上传本地图片情况,查询大量资料后发现对版本4.4兼容没有现成的解决方案,目前根据现有开源源码做个修改,可以支持兼容支持4.4版本上传图片: 具体是在onActivityResult 里多加了层判断: /* * 若当前版本API为19, 则把Uri路径转换成new File性质的Uri路径 * 若非 则按照之前方法调用即可

  •     在android开发工作中经常会遇到与附件相关的功能需求,有时候会遇到除了图片附件之外其他格式文件的处理需求。关于图片类型附件相关的处理(压缩,上传,下载)这里就不再累述。下面主要说下其他格式文件的处理。 一 PDF格式文件 展示:                 (1) https://github.com/JoanZapata/android-pdfview 此三方控件只支持项目ass

  • Android Studio没有看到LG G Pad 7.0 LTE(Android Studio not seeing LG G Pad 7.0 LTE) 我已经打开USB调试,但Android Studio没有播种我的设备。 但其他设备(三星Galaxy S3)播种 I have already turn on USB debugging but Android Studio not seed

  • apply plugin: 'com.android.application' ext { buildInfo = [ build_time : getFirstBuildTime(), vcs_version: getGitVersion(), app_name : "TOKENPICK" ] } de

  • android webview实现拍照 1. html <div id="pnlVideo1"> <input type="hidden" name="imgNric1" id="imgNric1" /> <label id="nric" class="control-label lab

  • 今天在接入腾讯企点客服的时候,用anroid自带的webView加载客服页面,当退出页面后重新进入时之前的聊天记录都被清空了,而直接在浏览器中打开对应的页面时历史聊天记录能正常显示,那么猜测我们的webView可能阻止了h5页面给本地写数据,查看客服页面的的源码发现它用到了Local Storage,而webView默认是不开启DOM Storage的,需要手动调用setDomStorageEna

 相关资料
  • JNI绑定 Android上的Java资源 WebView代码组织

  • Native.js for Android封装一条通过JS语法直接调用Native Java接口通道,通过plus.android可调用几乎所有的系统API。 方法: currentWebview: 获取当前Webview窗口对象的native层实例对象 newObject: 创建实例对象 getAttribute: 获取对象(类对象/实例对象)的属性值 setAttribute: 设置对象(类对

  • Android++ 是一个免费的 Visual Studio 扩展,用于支持在 Visual Studio 上开发和调试原生的 Android 应用,主要基于 NDK 的 C/C++ 应用。同时包括可订制的发布、资源管理以及集成了 Java 源码编译。

  • Android(安卓)是一种基于Linux内核的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由美国谷歌公司和开放手机联盟领导及开发。Android操作系统最初由Andy Rubin开发,主要支持手机。2005年8月由谷歌收购注资。2007年11月,谷歌与84家硬件制造商、软件开发商及电信营运商组建开放手机联盟共同研发改良Android系统。随后谷歌以Apache许可证的授

  • Android(安卓)是一种基于Linux内核的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由美国谷歌公司和开放手机联盟领导及开发。Android操作系统最初由Andy Rubin开发,主要支持手机。2005年8月由谷歌收购注资。2007年11月,谷歌与84家硬件制造商、软件开发商及电信营运商组建开放手机联盟共同研发改良Android系统。随后谷歌以Apache许可证的授

  • 简介 该库提供J2SE的Swing、AWT等类的安卓实现,引用该库便能在Android上运行J2SE应用程序。 该库实现大多数必需功能,但不是全部的J2SE。 成功示例HomeCenter服务器,该服务器基于J2SE,同时完全运行于Android之上。 使用指引 该库依赖于开源工程HomeCenter。 它不含Activity,需另建Android工程,并引用本库。 Activity和res需作为