Hey Guys,

I'm playing with android webview.. and I would like to have it running background whenever I press home button... Please let me know if this is possible... Here are the codes, maybe I need to tweak anything ..

package trektrak.GeoWebView;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class GeoWebViewActivity extends Activity {


    public class GeoWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // When user clicks a hyperlink, load in the existing WebView
            view.loadUrl(url);
            return true;
        }
    }


    public class GeoWebChromeClient extends WebChromeClient {
        @Override
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            // Always grant permission since the app itself requires location
            // permission and the user has therefore already granted it
            callback.invoke(origin, true, false);
        }
    }

    WebView mWebView;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mWebView = (WebView) findViewById(R.id.webView1);

        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.setWebViewClient(new GeoWebViewClient());

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setGeolocationEnabled(true);
        mWebView.setWebChromeClient(new GeoWebChromeClient());
        // I'm Loading the url ... 
        mWebView.loadUrl("");
    }

    @Override
    public void onBackPressed() {
        // Pop the browser back stack or exit the activity
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        }
        else {
            super.onBackPressed();
        }


        mWebView.setWebChromeClient(new WebChromeClient() {
          @Override
          public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota,
                       WebStorage.QuotaUpdater quotaUpdater)
          {
                quotaUpdater.updateQuota(spaceNeeded * 2);
          }
    });

    mWebView.getSettings().setDomStorageEnabled(true);


    mWebView.getSettings().setAppCacheMaxSize(1024*1024*10);


    String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
    mWebView.getSettings().setAppCachePath(appCachePath);
    mWebView.getSettings().setAllowFileAccess(true);
    mWebView.getSettings().setAppCacheEnabled(true);


}
}

so far, I enabled the webcached... and I need one more... I need it to be running on the background

Dani AI

Generated

Short answer: not reliably. Pressing Home transitions the Activity to the Paused/Stopped state (and the system can later kill the process), so a WebView inside an Activity is not a supported mechanism for continuing long-running background work. (developer.android.com)

WebView specifics: call its lifecycle methods so behavior is explicit — WebView.onPause()/onResume() and the static WebView.pauseTimers()/resumeTimers() control rendering, timers and geolocation handling; note that onPause() is a best-effort pause (it does not pause JavaScript timers — pauseTimers() does and is global to all WebViews). Example (safe to add to the Activity that hosts the WebView):

@Override
protected void onPause() {
  super.onPause();
  myWebView.onPause();       // pause rendering/geolocation where possible
  WebView.pauseTimers();     // pause JS timers globally
}

@Override
protected void onResume() {
  super.onResume();
  myWebView.onResume();
  WebView.resumeTimers();
}

Use those calls to avoid wasting CPU while hidden, but do not rely on the WebView to perform continuous background tasks. (developer.android.com)

If the page must keep doing real background work (continuous location, audio playback, sockets, periodic uploads), move that work out of the WebView and into the appropriate Android background API: a Foreground Service for continuous/real-time work (shows a persistent notification), or WorkManager / JobScheduler for deferrable or periodic tasks. For location tracking specifically, use the platform location APIs (FusedLocationProviderClient) from a Service and follow the runtime / Play-Console rules for background location (ACCESS_BACKGROUND_LOCATION and the Play review requirements). (developer.android.com)

Threading note and workflow tips: WebView and other Views must be used from the UI thread — do not try to “headless” a UI WebView on a background thread or service. Instead: implement background logic in a Service (foreground if continuous), expose updates (LocalBroadcast / bound Service / persistent storage), and when the Activity/WebView is visible push updates into the page with evaluateJavascript() or a JS bridge. For quick resume only (no continuous work) use WebView state saving/caching and explicit pause/resume calls instead of attempting to keep a WebView “running” while hidden. (developer.android.com)

Note: — if the goal is continuous geolocation or audio while Home is pressed, implement a Service/foreground service and surface results to the WebView when visible. — the suggestion to treat this as mobile/background-work is on point.

you might want to move this thread to mobile development

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.