Convert Figma logo to code with AI

delight-im logoAndroid-AdvancedWebView

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

2,388
574
2,388
52

Top Related Projects

Proof of concept Android WebView implementation based on Chromium code

Beautiful and customizable Android Activity that shows web pages within an app.

android java and javascript bridge, inspired by wechat webview jsbridge

AgentWeb is a powerful library based on Android WebView.

11,811

VasSonic is a lightweight and high-performance Hybrid framework developed by tencent VAS team, which is intended to speed up the first screen of websites working on Android and iOS platform.

Quick Overview

Android-AdvancedWebView is an enhanced WebView component for Android applications. It provides additional features and improvements over the standard WebView, making it easier for developers to integrate web content into their Android apps with advanced functionality and better performance.

Pros

  • Supports file uploads and downloads with progress tracking
  • Handles multiple windows and pop-ups efficiently
  • Provides easy-to-use JavaScript interfaces for communication between web and native code
  • Offers improved cookie handling and management

Cons

  • May require additional configuration for certain advanced features
  • Limited documentation for some of the more complex use cases
  • Potential compatibility issues with older Android versions
  • Slightly larger footprint compared to the standard WebView

Code Examples

  1. Basic usage of AdvancedWebView:
AdvancedWebView mWebView = findViewById(R.id.webview);
mWebView.setListener(this, this);
mWebView.loadUrl("https://example.com");
  1. Enabling file uploads:
mWebView.setGeolocationEnabled(false);
mWebView.setMixedContentAllowed(true);
mWebView.setCookiesEnabled(true);
mWebView.setThirdPartyCookiesEnabled(true);
  1. Handling JavaScript interfaces:
mWebView.addJavascriptInterface(new WebAppInterface(this), "Android");

// In JavaScript
Android.showToast("Hello from JavaScript!");
  1. Implementing file download listener:
@Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
    // Handle file download request
}

Getting Started

  1. Add the dependency to your build.gradle file:
dependencies {
    implementation 'com.github.delight-im:Android-AdvancedWebView:v3.2.1'
}
  1. Add the AdvancedWebView to your layout XML:
<im.delight.android.webview.AdvancedWebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
  1. Initialize and use the AdvancedWebView in your Activity or Fragment:
public class MainActivity extends AppCompatActivity implements AdvancedWebView.Listener {
    private AdvancedWebView mWebView;

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

        mWebView = findViewById(R.id.webview);
        mWebView.setListener(this, this);
        mWebView.loadUrl("https://example.com");
    }

    // Implement other necessary lifecycle methods and AdvancedWebView.Listener methods
}

Competitor Comparisons

Proof of concept Android WebView implementation based on Chromium code

Pros of chromeview

  • Uses the Chrome browser engine, providing better compatibility with modern web standards
  • Potentially faster rendering and JavaScript execution due to Chrome's optimizations
  • Seamless integration with Chrome Developer Tools for debugging

Cons of chromeview

  • Larger app size due to bundling Chrome components
  • May require more system resources compared to the native WebView
  • Less frequent updates as it's not actively maintained (last update in 2015)

Code comparison

Android-AdvancedWebView:

mWebView = (AdvancedWebView) findViewById(R.id.webview);
mWebView.setListener(this, this);
mWebView.loadUrl("https://example.com");

chromeview:

ChromeView webView = (ChromeView)findViewById(R.id.web_view);
webView.loadUrl("https://example.com");

Both libraries aim to enhance web browsing capabilities in Android apps, but they take different approaches. Android-AdvancedWebView extends the native WebView with additional features, while chromeview integrates the Chrome browser engine. Android-AdvancedWebView is more actively maintained and has a smaller footprint, making it suitable for most applications. chromeview offers potentially better web standards support and performance but at the cost of increased app size and resource usage. The choice between the two depends on specific project requirements and trade-offs between compatibility, performance, and app size.

Beautiful and customizable Android Activity that shows web pages within an app.

Pros of FinestWebView-Android

  • More customizable UI with extensive theming options
  • Built-in progress bar and menu items
  • Easier to implement with a fluent API

Cons of FinestWebView-Android

  • Larger library size due to additional features
  • Less focus on core WebView functionality
  • May require more setup for basic use cases

Code Comparison

FinestWebView-Android:

new FinestWebView.Builder(activity)
    .showUrl(false)
    .titleColor(Color.WHITE)
    .urlColor(Color.WHITE)
    .show(url);

Android-AdvancedWebView:

mWebView = findViewById(R.id.webview);
mWebView.setListener(this, this);
mWebView.loadUrl(url);

FinestWebView-Android offers a more fluent API for customization, while Android-AdvancedWebView provides a simpler setup for basic WebView functionality. FinestWebView-Android includes built-in UI elements and theming options, making it easier to create a polished web viewing experience. However, this comes at the cost of a larger library size and potentially more complex setup for simple use cases.

Android-AdvancedWebView focuses on core WebView functionality and provides a lightweight solution for integrating web content into Android apps. It may require more manual customization for advanced UI features but offers greater flexibility for developers who want more control over the WebView implementation.

Both libraries have their strengths, and the choice between them depends on the specific requirements of your project, such as the level of customization needed and the importance of minimizing library size.

android java and javascript bridge, inspired by wechat webview jsbridge

Pros of JsBridge

  • Supports bidirectional communication between JavaScript and native Android code
  • Provides a more flexible and customizable approach to JS-native interactions
  • Allows for asynchronous method calls from JavaScript to native code

Cons of JsBridge

  • Requires more setup and configuration compared to Android-AdvancedWebView
  • May have a steeper learning curve for developers new to JS-native bridging
  • Less focused on WebView-specific features and optimizations

Code Comparison

Android-AdvancedWebView:

webView.setListener(this, this);
webView.loadUrl("https://example.com");

JsBridge:

WebView webView = findViewById(R.id.webview);
BridgeWebView bridgeWebView = new BridgeWebView(webView);
bridgeWebView.registerHandler("nativeMethod", new BridgeHandler() {
    @Override
    public void handler(String data, CallBackFunction function) {
        // Handle native method call
    }
});

The code comparison shows that JsBridge requires more setup but offers greater flexibility in defining custom handlers for JavaScript-to-native communication. Android-AdvancedWebView provides a simpler setup focused on WebView functionality.

AgentWeb is a powerful library based on Android WebView.

Pros of AgentWeb

  • More comprehensive feature set, including file download management and JS injection
  • Better performance optimization with pre-loading and lazy loading
  • More active development and community support

Cons of AgentWeb

  • Larger library size, which may impact app size
  • Steeper learning curve due to more complex API
  • Primarily documented in Chinese, which may be challenging for non-Chinese speakers

Code Comparison

Android-AdvancedWebView:

webView = new AdvancedWebView(this);
webView.setListener(this, this);
webView.loadUrl("https://example.com");

AgentWeb:

AgentWeb.with(this)
    .setAgentWebParent(parentView, new LinearLayout.LayoutParams(-1, -1))
    .useDefaultIndicator()
    .createAgentWeb()
    .ready()
    .go("https://example.com");

Android-AdvancedWebView offers a simpler API for basic web view functionality, while AgentWeb provides a more feature-rich and customizable solution with a fluent API. AgentWeb's approach allows for easier configuration of advanced features, but may require more code for setup.

Both libraries aim to enhance the default Android WebView, but AgentWeb offers a more comprehensive solution at the cost of increased complexity and library size. The choice between the two depends on the specific requirements of your project and the level of customization needed.

11,811

VasSonic is a lightweight and high-performance Hybrid framework developed by tencent VAS team, which is intended to speed up the first screen of websites working on Android and iOS platform.

Pros of VasSonic

  • Offers a complete solution for hybrid app development, including both client-side and server-side optimizations
  • Provides advanced preloading and parallel loading techniques for faster page loads
  • Supports dynamic content updates without full page reloads

Cons of VasSonic

  • More complex setup and integration process compared to Android-AdvancedWebView
  • Requires server-side modifications to fully utilize its features
  • May have a steeper learning curve for developers new to hybrid app development

Code Comparison

Android-AdvancedWebView:

mWebView = (AdvancedWebView) findViewById(R.id.webview);
mWebView.setListener(this, this);
mWebView.loadUrl("https://example.com");

VasSonic:

SonicSessionConfig.Builder sessionConfigBuilder = new SonicSessionConfig.Builder();
sessionConfigBuilder.setSupportLocalServer(true);
SonicEngine.getInstance().runInMainThread(new Runnable() {
    @Override
    public void run() {
        SonicSession session = SonicEngine.getInstance().createSession(url, sessionConfigBuilder.build());
        if (null != session) {
            session.bindWebView(webView);
            session.loadUrl(url, null);
        }
    }
});

The code comparison shows that VasSonic requires more setup and configuration compared to Android-AdvancedWebView, but offers more advanced features for optimizing web content loading in hybrid apps.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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.