• Stars
    star
    2,387
  • Rank 19,265 (Top 0.4 %)
  • Language
    Java
  • License
    MIT License
  • Created almost 10 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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.

More Repositories

1

FreeGeoDB

Free database of geographic place names and corresponding geospatial data
PHP
1,586
star
2

HTML-Sheets-of-Paper

Word processor in your browser using HTML and CSS (for invoices, legal notices, etc.)
CSS
1,208
star
3

PHP-Auth

Authentication for PHP. Simple, lightweight and secure.
PHP
1,073
star
4

Faceless

[UNMAINTAINED] Faceless is where you can talk freely
Java
488
star
5

ShortURL

Bijective conversion between natural numbers (IDs) and short strings
C
381
star
6

Android-DDP

[UNMAINTAINED] Meteor's Distributed Data Protocol (DDP) for clients on Android
Java
273
star
7

PHP-PrivacyPolicy

Programmatically composable privacy policies for humans and machines
PHP
257
star
8

Android-SimpleLocation

Utility class for easy access to the device location on Android
Java
198
star
9

Knowledge

Random pieces of knowledge β€” with anecdotes and quotes
189
star
10

PHP-Cookie

Modern cookie management for PHP
PHP
165
star
11

MovieContentFilter

Watch movies with the freedom (not) to filter
PHP
142
star
12

Emoji

[UNMAINTAINED] Emoji (Unicode) and emoticon support for Java and Android
Java
95
star
13

AppRater

Android library that lets you prompt users to rate your application on their appstore (e.g. Google Play)
Java
75
star
14

Android-Languages

Custom language selection and access to language names for Android
Java
74
star
15

PHP-Str

Convenient object-oriented operations on strings
PHP
70
star
16

Android-Commons

[UNMAINTAINED] Reusable components and utilities for Android
Java
69
star
17

AndroidPatternLock

List of all combinations for the Android pattern lock
Java
69
star
18

PHP-FileUpload

Simple and convenient file uploads β€” secure by default
PHP
63
star
19

PHP-I18N

Internationalization and localization for PHP
PHP
57
star
20

Javadoc-to-Markdown

[UNMAINTAINED] Generate Markdown from your Javadoc, PHPDoc or JSDoc comments
JavaScript
56
star
21

JS-NeuralNetwork

Neural networks in JavaScript. Well-documented and object-oriented.
JavaScript
56
star
22

OpenSoccer

[UNMAINTAINED] Online Soccer Manager
PHP
51
star
23

PHP-DB

Safe and convenient SQL database access in a driver-agnostic way
PHP
47
star
24

Localize

[UNMAINTAINED] Collaborative Translation for Android
PHP
46
star
25

PHP-Router

Router for PHP. Simple, lightweight and convenient.
PHP
38
star
26

Android-Audio

High-level library for efficient playback of sounds and music on Android
Java
35
star
27

htaccess

.htaccess with reasonable defaults for most sites
ApacheConf
29
star
28

PHP-Foundation

Writing modern PHP applications efficiently
Shell
29
star
29

PHP-IDs

Short, obfuscated and efficient IDs for PHP
PHP
27
star
30

Secure-Firefox

Hardening Mozilla Firefox for maximum privacy and security
27
star
31

Android-Identicons

[UNMAINTAINED] Identicons for Android β€” turn any data into a visual hash
Java
23
star
32

PHP-Random

The most convenient way to securely generate anything random in PHP
PHP
22
star
33

PHP-GitScraper

Downloads entire Git repositories from publicly accessible ".git" folders over HTTP
PHP
20
star
34

PHP-HTTP

Hypertext Transfer Protocol (HTTP) utilities for PHP
PHP
18
star
35

Android-Countries

Provides country codes in accordance with ISO-3166-1 and localized names for each country
Java
18
star
36

PHP-Base64

Simple and convenient Base64 encoding and decoding for PHP
PHP
15
star
37

PHP-BaseConvert

Conversion of arbitrarily large numbers between any two bases or alphabets
PHP
15
star
38

NationSoccer

[UNMAINTAINED] Free 1-vs-1 soccer game for Android
Java
14
star
39

PHP-Temporal

Immutable date and time for PHP with a convenient interface
PHP
13
star
40

Java-Shapefile-Parser

Parses ESRI shapefiles and extracts all spatial/geometric data with attributes
Java
11
star
41

Android-WebRequest

Fluent interface for easy HTTP requests to web servers (GET, POST, PUT or DELETE)
Java
11
star
42

Android-Time

Library for displaying locale-specific time in Android
Java
10
star
43

Android-Tasks

[UNMAINTAINED] Helper classes for recurring and automatic tasks in Android
Java
9
star
44

AndroidDrawableResizer

[UNMAINTAINED] Automatic resizing of Android drawables from one density to all others
PHP
8
star
45

Java-Crash-ID

Generates unique fingerprints for crashes on Android and the JVM
Java
8
star
46

AndroidEmoji-PNG

[UNMAINTAINED] Android emoji from AndroidEmoji.ttf as single icons in PNG format
PHP
8
star
47

Android-KeyValueSpinner

Spinner component that works with normal values but additionally lets you use keys of an arbitrary class
Java
7
star
48

AndroidImageScraper

Extracts all image URLs from a given website ordered by file size
Java
7
star
49

MusikPlayer

Simple Music Player for Windows/Linux/Mac
Java
6
star
50

PHP-Foundation-Core

Core of β€œPHP-Foundation”
PHP
6
star
51

Android-InfiniteScrolling

Easily add infinite scrolling to ListView or GridView instances in Android
Java
5
star
52

2048

Fork of the popular game "2048"
CSS
5
star
53

Tools-for-Spotify

Tools and utilities for Spotify using the Spotify Web API
PHP
5
star
54

PHP-Alphabets

Sets of digits or characters that may be used for base conversions, encoding and decoding tasks, and input validation
PHP
4
star
55

Weather

Current weather data and hourly weather forecasts
PHP
4
star
56

JS-AbstractStorage

Flexible data storage for JavaScript backed by the Web Storage API
JavaScript
3
star
57

Maintenance

Simple and effective maintenance page for websites
PHP
3
star
58

Android-Monkey

[UNMAINTAINED] Library that generates pseudo-random streams of user input for Android apps
Java
3
star
59

JS-MediaPlayer

Convenient media playback with powerful controls in JavaScript
JavaScript
3
star
60

JS-PRNG

Pseudorandom number generator (PRNG) for JavaScript
JavaScript
2
star
61

2FA-Backup-Sheet

Create backup sheets for any service where you use two-factor authentication (2FA)
Shell
2
star
62

Batch-Renamer

Platform-independent utility for renaming batches of files
PHP
2
star
63

News60

Simple news aggregator and Twitter charts
PHP
2
star
64

PHP-OTP

One-time password (OTP) implementation for two-factor authentication with TOTP in accordance with RFC 6238 and RFC 4226
PHP
2
star
65

Requests

Logging and analysis of requests with optional static responses and redirects
Shell
2
star
66

Simple-ACRA-Storage

[UNMAINTAINED] Simple storage system for crash reports from ACRA on Android
PHP
2
star
67

Twitter-Charts-DE-AT-CH

Inofficial Twitter charts for Germany, Austria and Switzerland
1
star
68

Social-News-Germany

500 most-shared pieces from German online newspapers (March '13 β€” May '14)
1
star