Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách lưu cache WebView vào bộ nhớ cục bộ Android

Giới thiệu

Hướng dẫn này trình bày cách cấu hình WebView lưu cache vào bộ nhớ cục bộ (local storage) của ứng dụng để tải nhanh hơn khi truy cập lại trang web.

Các bước thực hiện

Bước 1: Tạo dự án mới

Tạo dự án Android Studio: File → New Project.

Bước 2: Layout activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Bước 3: MainActivity.java

package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.app.ProgressDialog;

public class MainActivity extends AppCompatActivity {

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

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Đang tải dữ liệu...");
        progressDialog.setCancelable(false);

        WebView webView = findViewById(R.id.web_view);
        webView.requestFocus();
        
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        
        // CẤU HÌNH CACHE
        webSettings.setAppCacheEnabled(true); // Bật cache ứng dụng
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); // Chế độ cache mặc định
        webSettings.setAppCachePath(getApplicationContext().getFilesDir().getAbsolutePath() + "/cache");
        
        // Các chế độ cache khác:
        // LOAD_CACHE_ONLY - Chỉ dùng cache, không tải mạng
        // LOAD_NO_CACHE - Không dùng cache, luôn tải mạng
        // LOAD_CACHE_ELSE_NETWORK - Dùng cache nếu có, nếu không tải mạng

        webView.loadUrl("https://touch.facebook.com/");

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress < 100) {
                    progressDialog.show();
                }
                if (newProgress == 100) {
                    progressDialog.dismiss();
                }
            }
        });
    }
}

Bước 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                

Giải thích cơ chế cache WebView

Các chế độ cache (setCacheMode)

Chế độHành vi
LOAD_DEFAULTSử dụng cache nếu không hết hạn, tải mạng nếu hết hạn (mặc định)
LOAD_NO_CACHELuôn tải từ mạng, bỏ qua cache
LOAD_CACHE_ONLYChỉ dùng cache, không bao giờ tải mạng (offline)
LOAD_CACHE_ELSE_NETWORKDùng cache nếu có (dù hết hạn), nếu không có mới tải mạng

Quản lý cache nâng cao

// Xóa toàn bộ cache
webView.clearCache(true);

// Xóa cache theo điều kiện
WebSettings settings = webView.getSettings();
settings.setAppCacheMaxSize(10 * 1024 * 1024); // Giới hạn 10MB

// Kiểm tra dung lượng cache
long cacheSize = getCacheDir().getUsableSpace();

Lưu ý quan trọng

  • Cache được lưu trong thư mục private của app (/data/data/package_name/cache), tự động bị xóa khi dung lượng thiết bị thấp.
  • Cần bật setAppCacheEnabled(true) trước khi set đường dẫn cache.
  • Cache chỉ hoạt động cho các resource có header cache-control hợp lệ từ server.
  • Để cache offline hoàn toàn, sử dụng LOAD_CACHE_ELSE_NETWORK kết hợp kiểm tra kết nối mạng.