// url represents the website containing the content to place into the cache.valconn:HttpsURLConnection=url.openConnection()asHttpsURLConnectionvalcurrentTime:Long=System.currentTimeMillis()vallastModified:Long=conn.getHeaderFieldDate("Last-Modified",currentTime)// lastUpdateTime represents when the cache was last updated.if(lastModified < lastUpdateTime){// Skip update}else{// Parse updatelastUpdateTime=lastModified}
Java
// url represents the website containing the content to place into the cache.HttpsURLConnectionconn=(HttpsURLConnection)url.openConnection();longcurrentTime=System.currentTimeMillis();longlastModified=conn.getHeaderFieldDate("Last-Modified",currentTime);// lastUpdateTime represents when the cache was last updated.if(lastModified < lastUpdateTime){// Skip update}else{// Parse updatelastUpdateTime=lastModified;}
如需采用更复杂的缓存方法,请考虑使用 Repository 设计模式。这需要创建一个自定义类(称为“存储区”),该类可针对某些特定数据或资源提供 API 抽象。存储库最初可能会从各种来源(例如远程 Web 服务)提取数据,但在后续调用中会向调用方提供数据的缓存版本。这种间接层可让您提供特定于应用的强大缓存策略。如需详细了解如何在应用中使用 Repository 模式,请参阅应用架构指南。
[null,null,["最后更新时间 (UTC):2025-08-21。"],[],[],null,["# Avoid unoptimized downloads\n\nSome of your app's users have intermittent access to the internet or have limits\non the amount of information they can download onto their devices. You can\nencourage users to interact with your app more often by reducing the amount of\ndata that your app needs to download.\n\nThe most fundamental way to reduce your downloads is to download only what you\nneed. In terms of data, that means implementing REST APIs that allow you to\nspecify query criteria that limit the returned data by using parameters such as\nthe time of your last update.\n\nSimilarly, when downloading images, it's good practice to reduce the size of\nimages server-side, rather than downloading full-sized images that are reduced\non the client.\n\nCache HTTP responses\n--------------------\n\nAnother important technique is to avoid downloading duplicate data. You can\nreduce the likelihood of downloading the same piece of data repeatedly by using\ncaching. By caching your app's data and resources, you create a local copy of\nthe information that your app needs to reference. If your app needs to access\nthe same piece of information multiple times over a short time period, you need\nto download it into the cache only once.\n\nIt's important to cache as aggressively as possible in order to reduce the total\namount of data that you download. Always cache static resources, including\non-demand downloads such as full-size images, for as long as reasonably\npossible. On-demand resources should be stored separately to enable you to\nregularly flush your on-demand cache to manage its size.\n\nTo ensure that your caching doesn't result in your app displaying stale data,\nuse the appropriate [HTTP status codes and\nheaders](https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching#validating_cached_responses_with_etags),\nsuch as the\n[`ETag`](https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.2)\nand\n[`Last-Modified`](https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.1)\nheaders. This allows you to determine when the associated content should be\nrefreshed. For example: \n\n### Kotlin\n\n```kotlin\n// url represents the website containing the content to place into the cache.\nval conn: HttpsURLConnection = url.openConnection() as HttpsURLConnection\nval currentTime: Long = System.currentTimeMillis()\nval lastModified: Long = conn.getHeaderFieldDate(\"Last-Modified\", currentTime)\n\n// lastUpdateTime represents when the cache was last updated.\nif (lastModified \u003c lastUpdateTime) {\n // Skip update\n} else {\n // Parse update\n lastUpdateTime = lastModified\n}\n```\n\n### Java\n\n```java\n// url represents the website containing the content to place into the cache.\nHttpsURLConnection conn = (HttpsURLConnection) url.openConnection();\nlong currentTime = System.currentTimeMillis();\nlong lastModified = conn.getHeaderFieldDate(\"Last-Modified\", currentTime);\n\n// lastUpdateTime represents when the cache was last updated.\nif (lastModified \u003c lastUpdateTime) {\n // Skip update\n} else {\n // Parse update\n lastUpdateTime = lastModified;\n}\n```\n\nYou can configure some networking libraries to respect these status codes and\nheaders automatically. When using\n[OkHttp](https://square.github.io/okhttp/), for example, configuring\na cache directory and cache size for the client will enable the library to use\nHTTP caching, as shown in the following code sample: \n\n### Kotlin\n\n```kotlin\nval cacheDir = Context.getCacheDir()\nval cacheSize = 10L * 1024L * 1024L // 10 MiB\nval client: OkHttpClient = OkHttpClient.Builder()\n .cache(Cache(cacheDir, cacheSize))\n .build()\n```\n\n### Java\n\n```java\nFile cacheDir = Context.getCacheDir();\nlong cacheSize = 10L * 1024L * 1024L; // 10 MiB\nOkHttpClient client = new OkHttpClient.Builder()\n .cache(new Cache(cacheDir, cacheSize))\n .build();\n```\n\nWith the cache configured, you can serve fully-cached HTTP requests directly\nfrom local storage, eliminating the need to open a network connection.\nConditionally-cached responses can validate their freshness from the server,\neliminating the bandwidth cost associated with the download. Uncached responses\nget stored in the response cache for future requests.\n\nYou can cache non-sensitive data in the unmanaged external cache directory by\nusing\n[`Context.getExternalCacheDir()`](/reference/android/content/Context#getExternalCacheDir()).\nAlternatively, you can cache data in the managed, secure application cache by\nusing\n[`Context.getCacheDir()`](/reference/android/content/Context#getCacheDir()).\nNote that this internal cache may be flushed when the system is running low on\navailable storage.\n| **Note:** Files stored in either cache location are erased when the app is uninstalled.\n\nUse a repository\n----------------\n\nFor a more sophisticated approach to caching, consider the Repository design\npattern. This involves creating a custom class, known as a Repository, which\nprovides an API abstraction over some specific data or resource. The repository\nmay initially fetch its data from various sources, such as a remote web service,\nbut provides callers with a cached version of the data in subsequent calls. This\nlayer of indirection allows you to provide a robust caching strategy that's\nspecific to your app. For more information about using the Repository pattern\nwithin your app, see the [Guide to app\narchitecture](/jetpack/guide)."]]