You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android Studio中实现WebView关闭时保存URL并重启加载

Save and Restore WebView URL on App Close/Reopen in Android Studio

Got it, let's walk through this step by step—this is a really common requirement, and Android gives us all the tools we need to make it work smoothly.

1. Use SharedPreferences for Persistent Storage

We'll use SharedPreferences to store the URL because it's lightweight, built-in, and perfect for small pieces of persistent data like this. It keeps the data even after the app is closed.

2. Save the Current URL in Real-Time

The best time to save the URL is whenever the WebView finishes loading a new page—this way, we always have the latest visited URL stored, even if the app crashes or is closed unexpectedly.

Add this code to your Activity/Fragment where you initialize the WebView:

// Define constants for preference keys and storage name (keep these consistent!)
private static final String KEY_SAVED_WEB_URL = "saved_webview_url";
private static final String PREFS_NAME = "WebViewSessionPrefs";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    WebView webView = findViewById(R.id.web_view);
    
    // Configure basic WebView settings (adjust based on your app's needs)
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true); // Enable if your app requires JavaScript

    // Set up WebViewClient to save URL whenever a page finishes loading
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            
            // Save the loaded URL to SharedPreferences
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
            prefs.edit()
                .putString(KEY_SAVED_WEB_URL, url)
                .apply(); // Use apply() for async, non-blocking save (better than commit())
        }
    });

    // ... rest of your WebView setup code
}

3. Restore the URL When the App Reopens

When your Activity starts up again, we'll check SharedPreferences for the saved URL and load it if it exists. Add this right after initializing the WebView:

// Retrieve the saved URL from SharedPreferences
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String savedUrl = prefs.getString(KEY_SAVED_WEB_URL, null);

if (savedUrl != null) {
    // Load the last visited URL
    webView.loadUrl(savedUrl);
} else {
    // Load your default fallback URL if no saved URL exists
    webView.loadUrl("https://your-default-homepage.com");
}

Extra Tips

  • If you specifically want to save only when the app is closed (not on every page load), you could move the save logic to onPause() or onDestroy() of your Activity. But saving on onPageFinished() is more reliable for capturing the latest page the user was viewing.
  • For Fragment-based setups, use requireActivity().getSharedPreferences(...) instead of getSharedPreferences().
  • Don't forget to add the INTERNET permission to your AndroidManifest.xml so the WebView can load URLs:
    <uses-permission android:name="android.permission.INTERNET" />
    

内容的提问来源于stack exchange,提问作者Tolu Olatubosun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:31:47