Search code examples
androidandroid-webview

Share a WebView between activities


I've written an iOS app that I want to port to android. This app is a front-end for a web-based timekeeping system at work. Unfortunately, the system doesn't have an API, so I'm screen-scraping it using xpath queries in javascript. In iOS, I only have to load this page once because I get full control over when instances of my UIWebView get destroyed.

The iOS app only has 3 use cases, each which break into separate Android activities:

  • Login
  • View a list of all reported times
  • Report a new time.

Using a naive approach, my android views (including the WebView I need to use to interact with the timekeeping system) will be destroyed and recreated when I switch between views. If I have to reload the WebView every time I switch activities, my app will appear very slow.

Is it possible to share a WebView instance between multiple activities? I know I can set the launchMode to singleInstance, but ideally, it would be nice to allow separate instances so that the back button would function normally.


Solution

  • Per a suggestion on from Eric Burke at STL Mobile Dev:

    See if your Android Application can create the WebView. You won't actually display the WebView anywhere, it's just created for interaction with the web site. The WebView instance's lifecycle is then managed by your Application rather than an Activity.

    I was able to share my WebView between my Activity instances. I specified a custom Application in my manifest, and created the WebView inside the Application. The Application is a Context and it lives as long as the app does, so all Activity objects can share the WebView that way.