Bart Simons

Bart Simons


Thoughts, stories and ideas.

Bart Simons
Author

Share


Tags


Twitter


Android WebView CPU Usage Fix

Bart SimonsBart Simons

Ever noticed the high CPU usage of a WebView element in your Android app? The CPU usage of my Android device rises above 50%, even when idle. This is the code of my activity (please note, everything is written in Kotlin and not Java):

package me.bartsimons.testapp

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        webLoginView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                view?.loadUrl(request?.url.toString())
                return false
            }

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                view?.loadUrl(url)
                return false
            }
        }

        webLoginView.loadUrl("https://bartsimons.me")
    }
}

And here is a quick look at my Android Profiler:

WebView usage at idle

After spending some time searching on Google I found out that the WebView timers are the culprit of this problem. Changing this line of code:

webLoginView.loadUrl("https://bartsimons.me")

To this:

webLoginView.loadUrl("https://bartsimons.me")

webLoginView.pauseTimers()
webLoginView.resumeTimers()

Fixed the problem for me. My app idles nicely at 0%. Very nice!

Bart Simons
Author

Bart Simons

Comments