In this article, I'm going to share with you how I built an Android app with web techs using WebView.
Download and install Android Studio.
Select Java as the development language (or Kotlin if you are familiar with it)
A lot of things, but let's just put our focus on the
MainActivity class, where we write our code and the
activity_main.xml, where we construct the app's layout.
activity_main.xml, remove everything under the root and add:
<WebView android:id="@+id/webapp" android:layout_width="match_parent" android:layout_height="match_parent" />
This creates a
WebView container which will display a web page in our app. The width and height are set to
match_parent which fills up the whole screen.
MainActivity class, add the following lines to
This searches for the WebView with the id
Now create an
assets folder under the root
app as shown in the screenshots below:
assets folder will contain the web resources we use in our app.
If the web resources are composed of plain HTML, CSS and JS, you can add them directly here, if they have a more complex composition such as some frameworks and bundlers, you might need to put the built version here instead, so the app will be of an optimal size.
Now that we had our Android app ready to display a web page, we need a web page. I keep this guide simple and easy by just adding an HTML file directly in the
assets folder with the following content:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h1>Good day!</h1> <p>You are viewing this web page from Android!</p> </body> </html>
Then add the following line to your
MainActivity class to load this page locally:
If you are going to serve the web page on a host, you may then replace the URL to point to the target host:
Now try running your app on a simulator or connected device, you should be able to see the result:
And that's it, we have just finished creating our Android app which is mainly constructed with web contents.
Under the same package as the
MainActivity, create a new class called
WebAppInterface with the following contents:
Our function to get the Android version is marked with the
MainActivity class, add:
This exposes any function we defined in the
And finally, in our HTML page, add the following script:
<script> document.body.append("Your device is using Android " + Android.getAndroidVersion()); </script>
Try running again and you should be able to see the Android version of your simulator or device.
A complete repository you can find at: https://github.com/khang-nd/android-web
And this concludes my sharing article, thank you for reading, see you in the next one.