قالب وردپرس درنا توس
Home / IOS Development / GeckoView Android Tutorial: Getting Started

GeckoView Android Tutorial: Getting Started

What if I told you that you could load a webpage or web content without using a WebView . Is it even possible? Yes, it is with GeckoView .

GeckoView is an open source library that lets you render web content on Android using the Gecko web engine. In this tutorial you will learn more about GeckoView and other Android tools used for web content.

Note : This tutorial assumes that you are already familiar with the basics of Android development. If you're completely new to Android development, read through the Android development training tutorials to familiarize yourself with the basics.

What is GeckoView?

GeckoView is an Android library that brings the Gecko web engine to the Android community. It was created by the community and the developers at Mozilla. The people at Mozilla have a lot of experience with the web and browsers in general.

Have you heard of FireFox? They are the people behind it. :]

FireFox and GeckoView both use the net engine Gecko. While GeckoView is a new library, it provides many cool open source apps such as FireFox Preview, FireFox Focus and FireFox Reality. You can even contribute to other wonderful projects run by GeckoView.

GeckoView vs WebView

WebView and GeckoView are not the same. GeckoView has its own API and does not replace anything. Here are some major differences between them:

  • While WebView was not designed to create browsers like GeckoView. It exposes the entire network's power to Android applications.
  • WebView can be updated, but the consistency of API and behavior may vary from device to device. This makes it more difficult to develop. On the other hand, GeckoView is self-sufficient. You send the entire API with your app so you get what you tested without surprises.
  • GeckoView complies with the web standards. In addition, it is supported by Mozilla, an organization with a history of fighting for the open network.
  • GeckoView provides access to and control of low-level APIs. It also has built-in support for private mode, tracking protection, WebVR and soon comes with Web Extensions support.

Finally GeckoView adds extra space to your final APK. For example, you can see a growth up to 30MB to 40MB from the library alone. This is because GeckoView includes the entire web engine with the app.

If you are considering GeckoView for your app, you can ask these questions:

  • Are you developing a browser-ish or similar app?
  • Do you need guaranteed access to APIs online?
  • Are you developing a game that relies on web technologies?

If you answered yes, GeckoView can be a great option for you. In contrast, if you only want to render any web content without API guarantees WebView may be the best option.

Getting Started

As you work on the tutorial, you create an app called AwesomeBrowser . There is a small browser that shows the power of GeckoView. It allows normal browsing and includes tracking protection enabled by default.

 Awesome Browser Demo

Download first AwesomeBrowser project using Download the materials button at the top or bottom of this tutorial. Then open the project in Android Studio 3.3 or later by selecting Open an existing Android Studio project on the Android Studio Welcome screen.

 Open an existing Android Studio project

Before continuing with the tutorial, take a look at the project structure.

Exploring the AwesomeBrowser Structure

This is the source code structure:

 AwesomeBrowser project structure [19659010] MainActivity.kt Here you will handle geckoView instance and toolbar.

  • Activity_main.xml Here you define the main setup.
  • Helpers.kt This contains a set of helper functions and constants.
  • As you can see in the picture above, there are several files I did not mention for the sake of brevity. You don't have to worry about them for this tutorial, but feel free if you're curious.

    Build and run the app. All you see is a blank screen until you add the user interface!

     blank screen

    Setting up GeckoView

    Begin with the start project. Currently, your primary goal is to configure GeckoView & # 39; s addiction and then load a page with it.

    GeckoView is distributed as a Gradle addiction and its objects live in maven.mozilla.org. To include it, at project level build.gradle add the stomach repository to the allprojects block just below center () .

    build .gradle

      stomachs {
    url "https://maven.mozilla.org/maven2/"

    This includes all the items in the stomach Mozilla depot.

    Then add the following code in the app ‣ build.gradle after applies: plugin lines, and before android block:

      ext {
    geckoview_channel = "nightly"
    geckoview_version = "70.0.20190712095934"

    Like FireFox, GeckoView has different channels for different purposes. These include the latest [stable] release, [beta] tested the release, and the nightly developer building . In this case, you have chosen the nightly building because you get the most up-to-date features and bug fixes.

    To keep things neat and tidy, you have added a variable for the version of Gecko to use and the channel from which you can retrieve it.

    Note : Take a look at API Changelog to see what changed from version to version. You can check the API documents for additional references.

    Then add the following to app ‣ build.gradle under buildTypes block, in android block:

     compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8

    Since GeckoView uses some Java 8 APIs, it requires these compatibility flags.

    Finally, for the last Gradle configuration, add the following code in dependencies block in the same file.

      implementation "org.mozilla.geckoview: geckoview - $ {geckoview_channel}: $ {geckoview_version}"

    Above you add the dependence for GeckoView addiction to the project.

    Synchronize your project with the graduate files now that you've made these changes.

    Adding some user interface

    To interact with GeckoView you need two main objects: a GeckoView widget and a GeckoSesssion .

    GeckoView Widget
    This is the user interface you want to use to render web content. It is a normal Android view you can create with either XML or code.

    A session represents a tab in a browser. It contains the URL you want to load and all additional configurations.

    Imagine you have a multi-tab browser.

    Each tab, or GeckoSession, has: [19659010] Condition attached to it.

  • Properties such as isPrivateMode enabled or disabled.
  • isDesktopMode enable or disable.
  • Its own browser history.
  • You want to keep all this information separated by tab and disconnected from the UI, widget GeckoView .

    This is a job for GeckoSession . It is an object that keeps all these configurations in one place, making it easy and easy to work with it.

    This powerful concept disconnects from the view, GeckoView from the state, GeckoSession . In this way, you can have a view, GeckoView responsible for rendering and multiple sessions, GeckoSession representing the state for each tab.

    This would be difficult to achieve using web view . Due to lack of sessions, it uses configurations directly on the viewer. : [

    A great way to customize how a session should behave is by providing a GeckoSessionSetting's object. You can do this by sending the setting object to the GeckoSession constructor.

    You create a setting object by using its builder GeckoSessionSettings.Builder (). Here's an example of how to do this:

        select settings = GeckoSessionSettings.Builder ()
    .usePrivateMode (true)
    .useTrackingProtection (true)
    .userAgentMode (USER_AGENT_MODE_MOBILE)
    .userAgentOverride ("")
    .suspendMediaWhenInactive (true)
    .allowJavascript (true)

    These are some other things you can configure on a session:

    Note that each GeckoSession has its own setting object. This lets you do a lot of customization without creating multiple instances of GeckoView . Remember the example of multiple tabs.

    Now that you understand how GeckoView widget and GeckoSession work, you can add them AwesomeBrowser .

    First, open Activity_main.xml to add the GeckoView widget. Replace TextView with GeckoView -widget below.


    Then connect it to the MainActivity.kt file.

    Add two private properties to MainActivity : a called geckoView UI widget, and another called geckoSession your tab:

      private lateinite was geckoView: GeckoView
    private selection geckoSession = GeckoSession ()

    Here you declare two properties so you can access them from different functions.

    Then create a function called setupGeckoView () . Remember to import all the new references.

      private fun setupGeckoView () {
    // 1
    geckoView = findViewById (R.id.geckoview)
    // 2
    choice runtime = GeckoRuntime.create (this)
    geckoSession.open (runtime)
    // 3
    geckoView.setSession (geckoSession)
    // 4
    geckoSession.loadUri ("about: buildconfig")

    How to do your code above:

    1. First, bind the GeckoView object from XML.
    2. You then create a GeckoRuntime who is responsible for keeping all of the conditions for the underlying Gecko engine.
    3. In order to load a URL you need a GeckoSession . Here you assign the to the GeckoView instance. In this way, GeckoView will know which info must be loaded.
    4. Finally, use the GeckoSession instance to load a URL. In this case, on: buildconfig an internal page showing all the configurations of this GeckoView building. This may be what url you want.

    As you know, the widget GeckoView has its own API. This code would look very different if you use a WebView .

    To use your new method, add a call to setupGeckoView () to the bottom of onCreate () :

      setupGeckoView ()

    You're almost ready to run the app. But first, you need to configure a proper build variant according to the device or emulator architecture that you are going to test on. Open the Build Variants window in Android Studio and select your architecture:

     Awesome Browser Build Variants

    You can see the emulator's CPU architecture by go to Tools ▸ AVD Manager . You will see it on the grid under CPU / ABI .

     Build Variant

    Most devices out there are based on ARM CPU architecture, but you need to verify yours.

    Now, build and run the app. :]

    If you have everything set up correctly, you will see this:

     Starter Project

    Over you loaded an internal page called about: buildconfig . There is a page that shows all the configurations of this GeckoView build, but you can replace it with whatever you want url .

    Note : When you do not select the correct build variant for the hardware CPU architecture, a common problem occurs. You get an error similar to this:
      Build Variant Error
    You can fix this by first selecting the correct build variant and then running the app again.

    Adding a Toolbar

    Having to recompile each time you want to load another site is not an ideal situation. In this section, you will focus on creating a toolbar that allows you to enter the URL you want to visit.

    Instead of having the URL hard-coded, update the setup to add a Toolbar . First, enter GeckoView into activity_main.xml with a RelativeLayout . The file should now look like this:


    Here you added a RelativeLayout that lets you control how the widgets setup. Now you can add Toolbar to the GeckoView widget.

    Add this code to RelativeLayout and over GeckoView :


    This toolbar contains a EditText you want to use to enter new URLs.

    Last, but not least, to make sure everything looks good, add this property to GeckoView to make sure it's rendered under Toolbar :

      android: layout_below = "@ id / toolbar"

    When set up, it is time to connect the input to EditText with GeckoView .

    Then go to MainActivity.kt file and then add a private property right under geckoSession .

      private lateinit was urlEditText: EditText

    You added a EditText to let you retrieve the specified URL.

    Then update the setupGeckoView () function which replaces the hard-coded URL geckoSession.loadUri ("about: buildconfig") with the two lines below:

      geckoSession. loadUri (INITIAL_URL)
    urlEditText.setText (INITIAL_URL)

    Here you updated the original URL to a constant value. When the app starts, it will load this URL. INITIAL_URL is a help constant and you can see the value in Helpers.kt .

    Then continue updating the URL with the contents of EditText . Add the following method after onCreate imported android.support.v7.app.ActionBar for ActionBar :

        private fun setupToolbar () {
    setSupportActionBar (findViewById (R.id.toolbar))
    supportActionBar? .displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM

    This indicates to the action bar that you should use a custom view, in this case EditText .

    Then add the onCommit () function. You will call this when a new URL is entered:

      fun onCommit (text: String) {
    if ((text.concepts (".") ||)
    text.concepts (":")) &&
    ! text.concepts ("")) {
    geckoSession.loadUri (text)
    } other {
    geckoSession.loadUri (SEARCH_URI_BASE + text)
    geckoView.requestFocus ()

    Here you update the new URL in the widget GeckoView . If the text entered is a URL, it is loaded. Otherwise, trigger a DuckDuckGo search.

    SEARCH_URI_BASE is a constant helper. It contains a parameterized url. You only add the search criteria by adding the text.

    Then add the setupUrlEditText () function to link it all:

      private fun setupUrlEditText () {
    urlEditText = findViewById (R.id.location_view)
    urlEditText.setOnEditorActionListener (object:
    View.On Focus ChangeListener, TextView.OnEditorActionLists {
    override fun onFocusChange (view: View ?, hasFocus: Boolean) = Device
    override fun onEditorAction (
    textView: TextView,
    actionId: Int,
    event: KeyEvent?
    ): Boolean {
    onCommit (textView.text.toString ())
    textView.hideKeyboard ()
    back true

    Here you add a listener for each time the user hits the enter key. In this way, it will know that the user will load the specified URL and call onCommit () when this occurs.

    Finally, make calls to this configuration. Inside the onCreate function, add these two new features, setupUrlEditText () and setupToolbar () just before setupGeckoView () .

      // 1
    setupToolbar ()
    // 2
    setupUrlEditText ()

    Here you:

    1. Set up the toolbar when the activity starts.
    2. Bind EditText and set a listener for when a new URL is entered.

    Phew, that's all right now. Build and run the app!

    Now you can enter the URL you want or perform a search with a word or phrase.

     AwesomeBrowser Demo

    Adding a progress bar

    Some pages take a long time to load, and there is no clear way to know if it is loading or not. Is it finished or is it still loading? Adding a toolbar will increase the user experience.

    For this job you need a ProgressBar and a way to know which state a page is in. Fortunately GeckoView provides an API for that. ProgressDelegate is an interface to observe the progress of a web page.

    The ProgressDelegate interface has different callbacks for the different statuses:

    • onPageStart : Dialed when content has started to load.
    • onPageStop : Called when content is fully loaded.
    • onProgressChange : Called each time the progress of a web page has changed.
    • onSecurityChange : Specifies when the security status is updated. It passes a SecurityInformation object that contains useful information about the site's security.

    To put all that together in code.

    First, go to the activity _main.xml file. Add a ProgressBar to RelativeLayout right after Toolbar and before GeckoView :

    Source link