Android webview open links in webview

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:

  1. src/main/java . Android Java source code.
  2. src/main/res . Resources used by the native application.
  3. src/main/res/drawable-_type_ . Image resources used by the native application.
  4. src/main/res/layout . XML layout files that define the structure of UI components.
  5. src/main/res/values . Dimensions, strings, and other values that you might not want to hard-code in your application.
  6. 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.

Читайте также:  Permission is only granted to system apps android

# 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:

  1. The WebView tries to load the original URL from the remote server, and gets a redirect to a new URL.
  2. 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).
  3. 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

Источник

9 Android WebView Examples In Kotlin & Java

Do you want to make an Android webview browser?

Don’t worry, I will help you to make a simple one.

Just like below. Android WebView browser

Download Source Code – Kotlin & Java

In this post, you will learn more about WebView. Okay, let’s start…

What is Android WebView?

There may be occasions when you want to show a webpage to your users such as Terms and conditions, app manual or your website and so on.

In a traditional way, we can send users to an external web browser but there is no guarantee that users would come back. So that’s one of the main reasons Android introduced a widget named WebView.

As the name suggests it helps to show or view online and offline web pages in our app. It’s available in android.webkit package and has abilities in history management, zooming, javascript, and CSS rendering.

From the beginning to now, WebView has grown a lot. Let’s check how it implemented in Android.

WebView to Android System Webview – implementation history

WebView was added in API level 1. It renders web pages using Webkit engine, which behind Apple’s Safari browser. Actually, WebKit makes an environment or views for the webpage to display on the app.

In Android 4.4, For better performance, Google decided to change webview rendering from stock webview to google’s chromium or blink.

Lots of bugs and fixes through os update, that made long time vulnerable. So Android engineers innovated a separate Android System Webview app that can install and update through Google’s app market Play store with next release “Lolipop”.

That made easy fixes in less time.

In Android 7.0, there is no need to enable Android System Webview app, Chrome will take care of webview. if it is disabled or uninstalled already, the system will use android system webview.

If both of them get disabled, webview will use stock Webkit engine and take care of your valuable web pages.

How to add WebView to your layout?

Webview can easily be added to your layout as any other view. You can just drag and drop webview or write code for that just like below

You can use it as a root element or as a child element. While using as a root element don’t forget to add XML namespace.

How To Create WebView Programmatically In Android?

For Kotlin users, I am using Android studio 3.1.2 and it uses Kotlin Android Extensions plugin by default. So there is no need to call findviewByid and cast. just use the id of the widget and call the methods.

Make sure Android Studio has imported these lines

Okay… Let’s start with our first example – Using the loadUrl() method.

Load Url – WebView Android Example In Kotlin & Java

We can easily load a webpage in webview using loadUrl() method. Just put your URL as a string, Before that, we must provide Internet permission in AndroidManifest.xml.

create a webview app in android with below code

If you are testing webview code in devices which contains Android System WebView version below 43.0.2357.121 or below Lolipop. If anyone below happens

  1. server side redirect
  2. Click on links in WebView

Then it might lead to opening an external browser. To force open all links in WebView, we need to set WebViewClient.

Sometimes You need to open your website links in webview and other links in external browsers. Then you can use the below sample code.

replace “www.example.com” with your site name.

But shouldOverrideUrlLoading (WebView view, String url) was deprecated in API level 24. So if you are planning to make an application for Nougat or above, then you can use

public boolean shouldOverrideUrlLoading (WebView view,WebResourceRequest request)

To open links in WebView in All devices use both shouldOverrideUrlLoading() methods just like

How To Play YouTube Video In WebView By Enabling JavaScript In Android

Let’s open youtube in our webview.

Use our first example, and replace URL in loadUrl with “https://www.youtube.com” and run.

You may see these type of actions:

  1. Youtube shows a progress bar loading.
  2. Bowser says Please enable JavaScript in your browser.

This is because of JavaScript. If you are a web developer, you already know the importance of javascript. If you don’t, Javascript is a client-side programming language, it helps us to provide validation, animations and popups and so on.

By default, Javascript is disabled on your browser. we can easily enable it by simple lines of code. how to enable javascript in android webview

Now you can start watching youtube videos in your webview.

Android WebView local file example

In this example, you will learn how to show a local HTML file in webview. We have already created a webpage for you. You can use that for a sample.

This is a local html file loaded from assets folder

Just make an assets folder in your project, Right click on app->New->Folder->Assets Folder. Now a dialog appears to change the location of assets folder. Leave it and Click Finish.

Place demo.html into assets folder and use below code

loadUrl() uses

LoadUrl() is a broad method and it works with:

    1. http:// and https:// URLs.

Eg: webview.loadUrl(“https://www.androidride.com”)
Webview.loadUrl(“//www.androidride.com”)

    1. Local filesystem URLs.

Don’t forget to add

In your AndroidManifest.xml.

    1. Application assets and resources URLs.

In URL, use android_asset not android_assets, yes, there is no ‘s’ at the end.

webview.loadUrl(“file:///android_res/mipmap/ic_launcher”)
There is no need for the file extension, but it won’t be a problem if you add it.

    1. content://URLs pointing content provider.

ERR_UNKNOWN_URL_SCHEME in Android WebView – Fixed.

In this example, You will learn how to solve ERR_UNKNOWN_URL_SCHEME in Android WebView. This type of error happens when WebView deals with UNKNOWN URL SCHEME links. Before that learn some basics.

Читайте также:  Realme unlock tool android 11

What is URL SHEME?

The URL scheme is something before the colon in the URL. actually, it’s the protocol describes how to access the resource.

WebView knows how to deal with HTTP, HTTPS, and file Schemes, but they don’t know what to do when these type of schemes come. ‘tel:’, ‘sms:’, and ‘mailto:’ and others.

So we have to tell webview to how to deal with those schemes in shouldOverrideUrlLoading() method. In this example, we are going to use ‘tel:’, ‘sms:’, ‘mailto:’, and ‘geo:’ links. When you click on them, each link will get opened with appropriate apps installed on your Android device.

demo.html

      • If it’s a network URL, WebView force the links to open in WebView,otherwise find a best option from Android System.

Create your webview app with the above code or you can download our example.

WebView loadData() example in Android

In this Android WebView example, we will show you how to render HTML code in Android WebView. It’s simple, Android API provides a method called loadData().

loadData() method needs 3 contents.

      1. String htmlData: This is our html content.
      2. String mimeType: here we use “text/html”.
      3. String encoding: most of the time, base64 or UTF-8.
      • It works with data,http and https schemes.
      • If you use other schemes, webview can’t access content due to javascript same origin policy.
      • You should use loadDataWithBaseURL(), if you want to use other schemes.

WebView loadDataWithBaseURL() example in Android

In this example, you will learn how to work with loadDataWithBaseURL() example. When you want to fetch an image from the assets folder using loadData() method. JavaScript origin policy restricts the access to content.

loadDataWithBaseURL() avoids this problem by specifying BaseURL. Using the Base URL, system resolve relative URLs in HTML content.

loadDataWithBaseURL() needs

  1. String baseURL: This URL is used to resolve relatvie URLs.
  2. String data: Html content that you want to show.
  3. String mimeType: mimeType of HTML data
  4. String encoding: encoding of html data
  5. String historyURL: This URL loads when you navigate back in webview

In this example, I am going to use the same loadData() code but just want to add image ‘ic_launcher’ from the mipmap folder.

Android WebView Download File example

In this android webview example, you will learn how to download a file using WebView and DownloadManager. Using DownloadManager, we can reduce code and leave the stress to DownloadManager. We also show AlertDialog for Download notification.

You can download the file using AsyncTask too.

Create a webview app project in Android Studio, Add below lines to AndroidManifest.xml

How To Run JavScript In Android WebView

I already said JavaScript has an important role in the web world. In Android, we can also make use of JavaScript by sending data to Javascript from Android and vice versa. But it also raises security issues too. If you are using any third-party code, make sure it’s not vulnerable to users security.

Android API provides a number of methods and classes to achieve a super web app. I have categorized them

JavaScript calling Kotlin/Java

      1. addJavascriptInterface()
      2. WebMessagePort – (6.0)

Kotlin/Java calling JavaScript

      1. loadUrl()
      2. evaluateJavascript() – (4.4)
      3. WebMessage – (6.0)

The numbers shown in the brackets means the starting API. We are not going to discuss WebMessagePort and WebMessage here. That will be updated later.

webview addJavascriptInterface example in android

webview addjavascriptinterface example in android

In this addJavascriptInterface example, we send a message from a local HTML webpage to Android and show it through a toast.

JavaScript can access methods in API level Build.VERSION_CODES.JELLY_BEAN_MR1 and above, if they are

      • defined as public
      • annotated with JavascriptInterface

sample.html

MainActivity.kt

how above code works?

      • JavaScript enabled.
      • Inject java object into webpage using addJavascriptInterface() method. It needs
        1. Java class object: The java class object which inject into webview
        2. String name: The name used to access java methods from JavaScript
        3. It’s better to remove java object from webview after the use

WebView evaluateJavascript example in Android

Let’s call javascript from Java. In this example, we receive the text from edittext and send it to the local HTML page. Use loadUrl() for below 4.4 and evaluateJavascript() works with KitKat and above.

sample.html

MainActivity.kt

Android WebView Browser example – Progress bar included

Finally, we are here. Let’s create a webview app browser. This browser has

      • ProgressBar support
      • Google search and load URL support
      • Download file support
      • YouTube video support
      • Navigate history and custom home page
      • Share Support

open your Android Studio.

Step 1

Start a new Android Studio project.

Application Name: WebView Browser
Company Domain: androidride.example.com

Step 2

Select form factors and minimum SDK

Select API 15: IceCreamSandwich and Click Next.

Step 3

Step 4

Add INTERNET and WRITE_EXTERNAL_STORAGE permission in AndroidManifest.xml

AndroidManifest.xml
      • android:windowSoftInputMode=”stateAlwaysHidden|adjustNothing” – it helps by without adjusting our bottom bar layout and disable the focus in EditText while startup.

Step 5

build.gradle

Step 6

Colors.xml

Step 7

Styles.xml

Step 8

activity_main.xml
      • android:layout_weight attribute used to hold widgets.
      • android:inputType=”textNoSuggestions” disable spell check
      • android:background=”?android:selectableItemBackground” – makes transparent

I have used vector asset icons, you can also access them by right clicking on res->New->Vector Asset->Click on clip Art and select your icons, you can change color and size. Click OK and Next.

Step 9

custom_progress.xml

Step 10

This browser has a simple home page, for that, we have to add local HTML file in the assets folder.

demo.html

Step 11

MainActivity.kt

Hey… Thanks for scrolling. If you find anything useful in this post, please share it.

Conclusion

WebView has an important role in Android programming. With a few lines of code, beginners can also easily load web pages in their app. You have learned to download the file and run javascript using Android WebView. I am sure that these examples make you better dealing with WebView. This is a small guide about WebView. You can also find more information from below links.

    • Building web apps in WebView
    • WebView | Android Developers

Источник

Оцените статью