- WebView
- Загружаем локальные страницы и картинки
- Загружаем данные при помощи loadData() и loadDataWithBaseURL()
- Проблемы с кодировкой
- Методы
- Используем зум для просмотра
- Прозрачность
- WebView в Lollipop
- Советы
- Касания экрана
- Настройки
- Ночной режим
- WebView for Android
- # Does this mean Chrome for Android is using the WebView?
- # Does the new WebView have feature parity with Chrome for Android?
- # What hardware sensor APIs are available to the new WebView?
- # What does the new WebView mean for developers?
- # How do I enable remote debugging?
- # Does the WebView support the Chrome Apps APIs?
- # Should I enable hardware acceleration?
- Try out WebView Beta, Dev, or Canary
- Contents
- Which channel do I want?
- How do I try a pre-release channel?
- Android 10 and later (Q, R, etc.)
- Returning to stable WebView
- Android 7 through 9 (Nougat/Oreo/Pie)
- Returning to stable WebView
- Android 5 or 6 (Lollipop/Marshmallow) and Android TV
- Returning to stable WebView
- Android 4.4 (KitKat) or earlier
- Reporting problems with pre-release WebView
- Work profile, multiple users, or Samsung Secure Folder
- Command line tools
- Getting Started: WebView-based Applications for Web Developers
- # Install Android Studio
- # Create a New Android Project
- # Add the WebView
- # Enable JavaScript
- # Load a Remote URL
- # Handling Navigation
- # Handling the Android Back Button
- # Loading HTML files from the file system
WebView
WebView — это компонент, который позволяет встраивать веб-страницы в приложения, своеобразный мини-браузер. Находится в разделе Containers.
В старых версиях Android WebView использовал движок WebKit. В Android 4.4 он стал использовать движок Chromium или Blink. В Android 5 появилось отдельное приложение System WebView, которое можно скачать из Play Market. Такое разделение позволило обновлять движок без обновления системы. На этом приключения не закончились. В Android 7.0 уже используется движок Chrome, а если этого браузера на устройстве нет, то используется System WebView. Подобные выкрутасы не прошли даром, программисты часто жалуются, что какой-то кусок кода не работает. Приходится проверять работу на разных устройствах.
Надеюсь, вы уже познакомились с базовым примером по созданию собственного браузера. Рассмотрим дополнительные возможности элемента WebView.
Загружаем локальные страницы и картинки
Если вы хотите загружать в WebView страницы не из интернета, а со своего приложения, то разместите нужные файлы в папке assets, например, assets/mypage.html. Доступ к файлу вы можете получить через конструкцию file://android_asset:
Аналогично поступаем с картинками, которые встречаются в html-файле
Также можно загрузить файл из папки res/raw:
Если картинка находится на внешнем накопителе, то попробуйте вариант:
Недавно наткнулся на фрагмент кода, где нужно добавить несколько новых настроек для работы с файлами. Пример для Kotlin.
Загружаем данные при помощи loadData() и loadDataWithBaseURL()
Данные можно загрузить с помощью метода loadData():
Если текст простой, то этот способ подойдёт. Но в данном примере встречается символ процента, который относится к спецсимволам и часть текста может оказаться недоступной. Если в тексте встречаются подобные символы, то лучше использовать метод loadDataWithBaseURL():
Если вам приходится использовать loadData(), то спецсимволы можно заменить при помощи метода replace():
Проблемы с кодировкой
У меня есть программа в Google Play, использующая WebView. К моему удивлению, некоторые пользователи жаловались, что текст нечитаем, так как они видят только кракозябры. Особенно много жалоб было от пользователей с планшетами. Оказалось, что проблема довольна распространённая и обсуждается на форумах. Танцы с бубнами (установка явной кодировки UTF-8) не помогают. Нашёл один ответ, который у некоторых заработал, на всякий случай я его здесь оставлю.
Но я рекомендую просто использовать метод loadDataWithBaseURL(). Работает стабильно.
Методы
У WebView есть множество методов, которые позволяют добиваться полной функциональности как у обычного браузера — обновить страницу, перейти на предыдущую страницу и т.д. Часть методов представлена ниже:
Используем зум для просмотра
Не забывайте, что WebView можно использовать не только для просмотра html-страниц, но и для просмотра изображений. Поэтому данный компонент вполне можно использовать просмотра картинок с котиками, к тому же вы можете включить встроенный механизм масштабирования:
Прозрачность
Устанавливать прозрачность лучше программно. Встречал жалобы, что через XML это свойство не работает.
WebView в Lollipop
В Android 5.0 компонент доступен в Google Play (Android System WebView) и его можно обновлять на устройстве.
Компонент теперь основывается на движке Chromium и поддерживает следующие новинки.
Можно ознакомиться с некоторыми примерами — GoogleChrome/chromium-webview-samples. Там есть примеры с WebRTC, полноэкранным режимом, касаниями экрана, выбора файла, работой с JavaScript-сценариями.
Кроме того, стал доступен Safe Browsing — механизм, предупреждающий об опасных ссылках. Включается через манифест.
Советы
Если вы заметили, что экран мерцает во время загрузки WebView, то поменяйте фон. Мерцание происходит из-за смены фона приложения (темы), на белый фон по умолчанию для WebView, а потом на фон, который прописан на странице.
Касания экрана
Так как поддерживаются касания экрана, то старайтесь использовать на веб-странице визуальные эффекты нажатия кнопок и других элементов при помощи псевдокласса :active, например, так:
Настройки
В API 24 появилась возможность открыть окно настроек и выбрать движок для WebView:
Ночной режим
Появилась поддержка тёмной темы в последних версиях WebView.
За ночной режим отвечает класс WebViewFeature, который имеет в своём составе коллекцию различных возможностей. Проверить поддержку той или иной возможности можно через isFeatureSupported().
Всего три варианта для тёмной темы.
- FORCE_DARK_OFF
- FORCE_DARK_AUTO
- FORCE_DARK_ON
Источник
WebView for Android
Published on Friday, February 28, 2014
Since Android 4.4 (KitKat), the WebView component is based on the Chromium open source project. WebViews now include an updated version of the V8 JavaScript engine and support for modern web standards previously missing in old WebViews. New Webviews also share the same rendering engine as Chrome for Android, so rendering should be much more consistent between the WebView and Chrome.
In Android 5.0 (Lollipop), the WebView has moved to an APK so it can be updated seperately to the Android platform. To see what version of Chrome is currently used on a Lollipop device, simply go to Settings XMLHttpRequest s made from JavaScript. Those requests always use the default user-agent string.
# Does this mean Chrome for Android is using the WebView?
No, Chrome for Android is separate from WebView. They’re both based on the same code, including a common JavaScript engine and rendering engine.
# Does the new WebView have feature parity with Chrome for Android?
For the most part, features that work in Chrome for Android should work in the new WebView.
Chrome for Android supports a few features which aren’t enabled in the WebView, including:
Feature | WebView v30 | WebView v33 | WebView v36 |
---|---|---|---|
WebGL | x | x | ✓ |
WebRTC | x | x | ✓ |
WebAudio | x | x | ✓ |
Fullscreen API | x | x | x |
Form validation | x | ✓ | ✓ |
Filesystem API | x | x | x |
File input type | x | x | x |
x | ✓ | ✓ |
# What hardware sensor APIs are available to the new WebView?
Some HTML5 APIs can be used to access the hardware sensors on an Android device. Chrome for Android supports a few of these APIs but not all of them are currently enabled in the WebView.
API | WebView v30 | WebView v33 |
---|---|---|
Geolocation API (requires android.permission.ACCESS_COARSE_LOCATION and/or android.permission.ACCESS_FINE_LOCATION permissions) | ✓ | ✓ |
Device Orientation API | x | x |
Media Capture and Streams | x | x |
Vibration API (requires android.permission.VIBRATE permission) | x | ✓ |
# What does the new WebView mean for developers?
This is a big change from the original WebView as it brings a new set of HTML5 feature support, improved JavaScript performance, and remote debugging of web content using the Chrome DevTools.
There are some changes that will affect existing apps.
If you are currently using content:// URLs to load files from a content provider in your application, note that these URLs only work when accessed from local content. That is, web content hosted outside your application is not allowed to access files built into your application.
There are a small number of other changes that might impact your application. Read the migration guide for more information.
# How do I enable remote debugging?
# Does the WebView support the Chrome Apps APIs?
No. The Chrome Apps platform isn’t yet supported on Android.
# Should I enable hardware acceleration?
Hardware acceleration is enabled by default. If you are explicitly disabling it for older versions of Android you should try enabling it for KitKat based devices and see if it improves performance.
Last updated: Friday, February 28, 2014 • Improve article
Источник
Try out WebView Beta, Dev, or Canary
Using a pre-release channel of WebView allows you to test new, upcoming features and enhancements to WebView. This is especially useful for Android app developers who use WebView in their apps.
Contents
Which channel do I want?
Like Chrome, WebView has four release channels:
- Stable channel
- Installed and updated by default on every Android device with WebView
- Fully tested; least likely to crash or have other major bugs
- Updated every 2-3 weeks with minor releases, and every 6 weeks with major releases
- Beta channel
- Available on Android 5 (Lollipop) and later
- Tested before release, but not as extensively as stable
- One major update ahead of stable, minor updates every week
- Dev channel
- Publicly available on Android 7 (Nougat) and later
- Two major updates ahead of stable, representing what is actively being developed
- Updated once per week
- Minimally tested
- Canary build
- Available on Android 7 (Nougat) and later
- Released daily
- Includes the latest code changes from the previous day
- Has not been tested or used
If you’re looking for a specific of version of chromium, the latest versions released to each channel can be found on Chromium Dash. WebView and Chrome for Android always release together on all OS levels.
On Android 7 (Nougat) and later, you can install multiple channels at the same time. This allows you to play with our latest code, while still keeping a tested version of WebView around.
How do I try a pre-release channel?
Steps depend on your version of Android:
Android 10 and later (Q, R, etc.)
Pre-release channels must be downloaded and installed as separate apps, but only one must be chosen to provide the system’s WebView implementation at any given time.
Download a pre-release channel of WebView from the play store, available here:
Choose Developer Options > WebView implementation (see figure)
Choose the channel that you would like to use for WebView
Returning to stable WebView
- To return to WebView stable, select “Android System WebView” again in the WebView implementation menu
Android 7 through 9 (Nougat/Oreo/Pie)
Pre-release channels must be downloaded and installed as separate apps, but only one must be chosen to provide the system’s WebView implementation at any given time.
Download a pre-release channel of Chrome from the play store, available here:
Choose Developer Options > WebView implementation (see figure)
Choose the Chrome channel that you would like to use for WebView
Returning to stable WebView
- To return to WebView stable, select Chrome again in the WebView implementation menu
Android 5 or 6 (Lollipop/Marshmallow) and Android TV
Only one installation of WebView is allowed, but users can opt to receive the latest beta updates from the Play Store.
- Join the beta tester program on Google Play
- On your device, update Android System Webview in the Play Store
- When the Play Store finishes updating, you will be using WebView beta!
Returning to stable WebView
- Leave the tester program
- Uninstall all updates by visiting Settings > Apps > Android System WebView > Three dots menu in the top right > Uninstall updates
- Visit the Play Store page one more time to install the latest updates to WebView stable, which will include important security fixes.
Android 4.4 (KitKat) or earlier
WebView does not receive updates on these versions of Android, so the pre-release channels of WebView are not available.
Reporting problems with pre-release WebView
Any WebView-related bugs can be filed here.
To best enable us to resolve the issue, please ensure you provide all of the information requested in the bug report template.
Work profile, multiple users, or Samsung Secure Folder
If your Android device has been configured with a work profile, you‘ll need to install pre-release WebView for both your work profile and regular profile. You can only change WebView channel if you’ve enabled this for all profiles on the device. Then you should be able to successfully switch WebView channels following the steps above.
Some devices may support multiple user accounts. Similar to work profile, your pre-release WebView channel must be installed and enabled for each user account on the device.
Some Samsung phones support a feature called Secure Folder. Under the hood, this is implemented by creating a new user profile, similar to work profile or multiple users. If you‘ve previously enabled the Secure Folder feature, you’ll need to add your WebView channel to the folder. Open the folder, click “add apps,” and select the desired WebView channel. Then you should be able to select WebView from the menu above.
Command line tools
Choosing your WebView implementation on Android 7 (Nougat) or later can also be done using adb, instead of the Settings UI:
Источник
Getting Started: WebView-based Applications for Web Developers
Published on Friday, February 28, 2014
Getting started with the Android WebView is fairly simple, whether you want load a remote URL or display pages stored in your app.
This tutorial walks you through creating a new Android Project, adding a WebView, loading a remote URL, and then loading a local HTML page.
Note: This tutorial assumes you’re a developer with limited or no experience with the Android development environment, but have some experience with Java. If you’re already familiar with programming for Android, you may want to refer to to Building Web Apps in WebView on the Android developer site instead.
# Install Android Studio
This tutorial uses Android Studio, the new design-and-build IDE for Android. So you’ll need start off by installing Android Studio, as described here:
# Create a New Android Project
When the installation completes, Android Studio launches and displays the welcome screen.
To create a new project:
Click New Project.
On the next page, enter your application name, package name and target SDKs, and click Next.
Note: If you only intend to support the Chromium WebView (rather than the old WebKit WebView) set Minimum required SDK to API 19: Android 4.4 (KitKat).
On the next page, you’re prompted to enter an application icon. (You can change the icon later, so don’t worry if you don’t have one right now.) When you’re done, click Next.
The next page lets you select the main Android activity for your application. For the purposes of this guide, select Blank Activity and click Next.
Note: An Android Activity can be viewed as a screen of an app. In this case, the application’s main activity will hold the web view. If you’re planning to venture further into native Android development, you can find more information in the Android Activities API guide
The next page lets you change the names for the default Activity and layout. Click Finish to accept the defaults and create the project.
You now have a new Android project. Next, to add the WebView!
Note: After you have your project created, make sure you have the KitKat SDK installed. Go to Tools > Android > SDK Manager and make sure you have Android 4.4 (API 19) installed.
# Add the WebView
Android Studio will give you some boilerplate code to set up your application. Your project’s structure should look something like this:
A few of the more import folders are identified in the picture:
- src/main/java . Android Java source code.
- src/main/res . Resources used by the native application.
- src/main/res/drawable-_type_ . Image resources used by the native application.
- src/main/res/layout . XML layout files that define the structure of UI components.
- src/main/res/values . Dimensions, strings, and other values that you might not want to hard-code in your application.
- src/main/AndroidManifest.xml . The manifest file defines what’s included in the application: activities, permissions, themes, and so on.
You need to add a WebView to the main activity’s layout.
Open the activity_main.xml file in the src/main/res/layout directory if it is not already open. (You may also see a fragment_main.xml file. You can ignore this, as it’s not required for this tutorial.)
Select the Text tab at the bottom of the of the activity_main.xml editor to see the XML markup.
This file defines the layout for your main activity, and the Preview panes show the a preview of the activity. The Blank Activity layout doesn’t include any children. You’ll need to add the WebView.
In the XML pane, remove the self-closing slash from the end of the FrameLayout element, and add the element and a new closing tag, as shown:
To use the WebView you need to reference it in the Activity. Open the Java source file for the main activity, MainActivity.java in the src/main/java/
Add the lines shown in bold.
The existing code in the onCreate method does the work of hooking up the Activity with the layout. The added lines create a new member variable, mWebView , to refer to the web view.
Remove the following code:
The WebView is identified by the resource ID, which is specified by this line in the layout file:
After adding the code, you’ll see some warning messages in the margin of the editor. This is because you haven’t imported the right classes for WebView. Luckily Android Studio can help you fill in the missing classes. The easiest way to do this is click and hover over an unknown class name and wait for a popup showing a «quick fix» — in this case, adding an import statment for the WebView class.
Press Alt + Enter (Option + Enter on Mac) to accept the quick fix.
WebView in hand you can move on to setting it up and and loading some juicy web content.
# Enable JavaScript
WebViews don’t allow JavaScript by default. To run a web application in the web view, you need to explicitly enable JavaScript by adding the following lines to the onCreate method:
# Load a Remote URL
If you’re going to load data from a remote URL, your application needs permission to access the internet. This permission needs to be added in the application’s manifest file.
Open the AndroidManifest.xml file in the src/res directory. Add the line in bold before the closing tag.
The next step is to call the loadUrl method on the webview. Add the following line to the end of the onCreate method.
Now try running the project. If you don’t have a device handy, you can create an emulator (AVD or Android Virtual Device) by going to Tools > Android > AVD Manager.
Note: To detect when a URL has started and finished loading, use WebViewClient.onPageStarted and WebViewClient.onPageFinished .
# Handling Navigation
Now try changing the URL you’re loading to http://www.html5rocks.com/ and rerun your application. You’ll notice something strange.
If you run the application now with a site that has a redirect like html5rocks.com , your app ends up opening the site in a browser on the device, not in your WebView — probably not what you expected. This is because of the way the WebView handles navigation events.
Here’s the sequence of events:
- The WebView tries to load the original URL from the remote server, and gets a redirect to a new URL.
- The WebView checks if the system can handle a view intent for the URL, if so the system handles the URL navigation, otherwise the WebView will navigate internally (i.e. the user has no browser installed on their device).
- The system picks the user’s preferred application for handling an http:// URL scheme — that is, the user’s default browser. If you have more than one browser installed, you may see a dialog at this point.
If you’re using a WebView inside an Android application to display some simple web content (for example, a help page), this may be exactly what you want to do. However, for more sophisticated applications, you may want to handle the navigation links yourself.
To handle navigation inside the WebView you need to override the WebView’s WebViewClient , which handles various events generated by the WebView. You can use it to control how the WebView handles link clicks and page redirects.
The default implementation of WebViewClient makes any URL open in the WebView:
This is a good step forward, but what if you want to handle links for your site only, while opening other URLs in a browser?
To achieve this you need to extend the WebViewClient class and implement the shouldOverrideUrlLoading method. This method is called whenever the WebView tries to navigate to a different URL. If it returns false, the WebView opens the URL itself. (The default implementation always returns false, which is why it works in the previous example.)
Create a new class:
Right-click the package name of your app and select New > Java Class
Enter MyAppWebViewClient as the class name and click OK
In the new MyAppWebViewClient.java file, add the following code (changes shown in bold):
The new code defines MyAppWebViewClient as a subclass of WebViewClient and implements the shouldOverrideUrlLoading method.
The shouldOverrideUrlLoading method is called whenever the WebView is about to load a URL. This implementation checks for the String «html5rocks.com» at the end of the host name of the URL. If the string exists, the method returns false, which tells the platform not to override the URL, but to load it in the WebView.
For any other hostname, the method makes a request to the system to open the URL. It does this by creating a new Android Intent and using it to launch a new activity. Returning true at the end of the method prevents the URL from being loaded into the WebView.
To use your new custom WebViewClient, add the following lines to your MainActivity class:
Now, a user can click any of the HTML5Rocks links and stay within the app, but links to external sites are opened in a browser.
# Handling the Android Back Button
As you start playing around and navigating the awesome HTML5Rocks articles, hitting the back button on Android exits the application, even though you’ve explored a few pages of the site.
WebView has a method canGoBack which tells you if there is anything on the page stack that can be popped. All you need to do is detect a back button press and determine if you should step back through the WebView’s history or allow the platform to determine the correct behaviour. Inside your MainActivity class, add the following method (in bold):
# Loading HTML files from the file system
A big advantage of using a WebView inside an installable application is that you can store assets inside the app. This lets your app work offline and improves load times, since the WebView can retrieve assets directly from the local file system.
To store files such as HTML, JavaScript, and CSS locally, put them in the assets directory. This is a reserved directory that Android uses for raw files that your app may need access to (i.e. files it knows it should minimise or compress).
In your project, create the assets directory in main ( src/main/assets ).
Generally it’s good practice to keep your web files in a subdirectory, so create a www directory and put all your web content in it.
Note: Absolute paths do not work in the WebView when referring to other files, such as CSS and JavaScript. So make sure you make all references relative, instead of absolute (for example, instead of «/pages/somelink.html», use «./pages/somelink.html»).
Once you have everything in your assets directory, it’s as simple as loading in the appropriate file:
You’ll want to tweak the shouldOverrideUrlLoading method so it opens a browser for non-local pages:
Now you are set to build a great WebView app!
For tips on getting the visuals just right, see Pixel-Perfect UI in the WebView.
If you run into trouble, the Chrome DevTools are your friends. See Remote Debugging on Android to get started.
Last updated: Friday, February 28, 2014 • Improve article
Источник