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

WebView加载Firebase PDF返回后重启空白,求修复方案

Fixing WebView Blank Screen Issue When Loading Firebase PDF

Let's break down what's causing the blank screen and how to fix it step by step:

Key Issues in Your Original Code:

  1. Missing PDF URL persistence: If your activity gets recreated (e.g., screen rotation), you lose the Pdf_data value, leading to an empty URL load.
  2. Duplicate WebView configuration: Calling ShowContent() in both onCreate and onResume re-sets up WebView clients/settings multiple times, causing conflicts.
  3. Unnecessary postDelayed: The 400ms delay can lead to duplicate load requests when the activity resumes, disrupting the WebView state.
  4. Lack of error handling: You can't diagnose why loads fail without an error callback.
  5. Potential cache conflicts: Stale cached content might be displayed instead of the fresh PDF.

Corrected Code with Fixes:

First, update your member variables and add state saving:

public class ShowPdfActivity extends AppCompatActivity {
    private WebView webView;
    private ProgressDialog progressDialog;
    private String Pdf_data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_pdf);
        webView = findViewById(R.id.webView);

        // Restore PDF URL if activity was recreated
        if (savedInstanceState != null) {
            Pdf_data = savedInstanceState.getString("PDF_URL");
        } else {
            // Get PDF URL from intent (adjust the key to match your intent extra)
            Pdf_data = getIntent().getStringExtra("PDF_DATA");
        }

        // Initialize WebView settings once
        initWebView();
        // Load the PDF content
        loadPdfContent();
    }

    // Save PDF URL to survive activity recreation
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("PDF_URL", Pdf_data);
    }

Next, add the WebView initialization method (called once in onCreate):

private void initWebView() {
        webView.setWebChromeClient(new WebChromeClient());
        WebSettings webSettings = webView.getSettings();
        
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); // Prevent stale cache
        webSettings.setDomStorageEnabled(true); // Improve viewer compatibility

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                showProgressDialog();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                hideProgressDialog();
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                hideProgressDialog();
                Toast.makeText(ShowPdfActivity.this, "Failed to load PDF: " + description, Toast.LENGTH_SHORT).show();
            }
        });
    }

Add helper methods for progress dialog and PDF loading:

private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("Please Wait");
            progressDialog.setMessage("Previewing your Content ..");
            progressDialog.setIcon(R.mipmap.ic_launcher_round);
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    private void hideProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    private void loadPdfContent() {
        if (TextUtils.isEmpty(Pdf_data)) {
            Toast.makeText(this, "No PDF URL available", Toast.LENGTH_SHORT).show();
            return;
        }

        String encodedUrl;
        try {
            encodedUrl = URLEncoder.encode(Pdf_data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Toast.makeText(this, "Error encoding PDF URL", Toast.LENGTH_SHORT).show();
            return;
        }

        // Use proper & instead of HTML entity &
        String viewerUrl = "http://drive.google.com/viewerng/viewer?embedded=true&url=" + encodedUrl;
        webView.loadUrl(viewerUrl);
    }

Update lifecycle methods to handle resume and cleanup properly:

@Override
    protected void onResume() {
        super.onResume();
        // Reload PDF to ensure fresh content when returning to the activity
        loadPdfContent();
    }

    private void destroyWebView() {
        hideProgressDialog(); // Clean up progress dialog first

        if (webView != null) {
            webView.stopLoading();
            webView.clearHistory();
            webView.clearCache(true);
            webView.loadUrl("about:blank");
            webView.pauseTimers();
            webView.removeAllViews();
            webView.destroy();
            webView = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyWebView();
    }
}

Key Fixes Explained:

  • URL Persistence: Saving Pdf_data in onSaveInstanceState ensures we don't lose the URL if the activity is recreated.
  • One-Time Initialization: initWebView() sets up WebView settings and clients once, avoiding duplicate configurations.
  • Cache Control: LOAD_NO_CACHE prevents stale cached content from being displayed.
  • Error Handling: onReceivedError helps diagnose loading failures and informs the user.
  • Clean Progress Dialog Management: Ensures no memory leaks and proper dismissal.
  • Direct Load Without Delay: Removes the unnecessary postDelayed to avoid duplicate load requests.

If the PDF URL from Firebase is short-lived (expires after some time), you'll need to fetch a fresh URL from Firebase in onResume instead of reusing the old one. Otherwise, the above fixes should resolve the blank screen issue.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 22:57:33