با مجموعهها، منظم بمانید
ذخیره و طبقهبندی محتوا براساس اولویتهای شما.
برخی از کاربران برنامه شما به طور متناوب به اینترنت دسترسی دارند یا محدودیت هایی در میزان اطلاعاتی که می توانند در دستگاه های خود بارگیری کنند دارند. میتوانید با کاهش حجم دادهای که برنامه شما برای دانلود نیاز دارد، کاربران را تشویق به تعامل بیشتر با برنامهتان کنید.
اساسی ترین راه برای کاهش دانلودها این است که فقط آنچه را که نیاز دارید دانلود کنید. از نظر داده، این به معنای پیادهسازی APIهای REST است که به شما امکان میدهد با استفاده از پارامترهایی مانند زمان آخرین بهروزرسانی، معیارهای پرس و جو را تعیین کنید که دادههای برگشتی را محدود میکند.
به طور مشابه، هنگام بارگیری تصاویر، به جای دانلود تصاویر با اندازه کامل که در مشتری کاهش می یابد، تمرین خوبی است که اندازه تصاویر سمت سرور را کاهش دهید.
پاسخ های HTTP را کش
روش مهم دیگر جلوگیری از دانلود داده های تکراری است. میتوانید با استفاده از حافظه پنهان، احتمال بارگیری مکرر همان قطعه داده را کاهش دهید. با ذخیره داده ها و منابع برنامه خود، یک کپی محلی از اطلاعاتی که برنامه شما باید به آن ارجاع دهد ایجاد می کنید. اگر برنامه شما باید چندین بار در یک بازه زمانی کوتاه به یک قسمت از اطلاعات دسترسی پیدا کند، باید آن را فقط یک بار در حافظه پنهان دانلود کنید.
مهم است که تا جایی که ممکن است به طور تهاجمی حافظه پنهان ذخیره کنید تا کل دادههایی را که دانلود میکنید کاهش دهید. همیشه منابع استاتیک، از جمله دانلودهای درخواستی مانند تصاویر در اندازه کامل را تا زمانی که ممکن است در حافظه پنهان نگه دارید. منابع درخواستی باید به طور جداگانه ذخیره شوند تا بتوانید به طور منظم کش درخواستی خود را برای مدیریت اندازه آن شستشو دهید.
برای اطمینان از اینکه حافظه پنهان منجر به نمایش دادههای قدیمی در برنامه شما نمیشود، از کدها و سرصفحههای وضعیت HTTP مناسب مانند ETag و Last-Modified header استفاده کنید. این به شما امکان می دهد تعیین کنید که محتوای مرتبط چه زمانی باید به روز شود. به عنوان مثال:
کاتلین
// 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}
جاوا
// 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;}
می توانید برخی از کتابخانه های شبکه را به گونه ای پیکربندی کنید که به صورت خودکار به این کدهای وضعیت و سرصفحه ها احترام بگذارند. برای مثال، هنگام استفاده از OkHttp ، پیکربندی یک دایرکتوری کش و اندازه حافظه پنهان برای مشتری، کتابخانه را قادر میسازد تا از حافظه پنهان HTTP استفاده کند، همانطور که در نمونه کد زیر نشان داده شده است:
با پیکربندی کش، میتوانید درخواستهای HTTP کاملاً کش شده را مستقیماً از فضای ذخیرهسازی محلی ارائه دهید و نیازی به باز کردن اتصال شبکه را از بین ببرید. پاسخهای ذخیرهشده مشروط میتوانند تازگی خود را از سرور تأیید کنند و هزینه پهنای باند مرتبط با دانلود را حذف کنند. پاسخهای ذخیره نشده در حافظه پنهان پاسخ برای درخواستهای آینده ذخیره میشوند.
با استفاده از Context.getExternalCacheDir() می توانید داده های غیر حساس را در دایرکتوری حافظه پنهان خارجی مدیریت نشده ذخیره کنید. از طرف دیگر، میتوانید با استفاده از Context.getCacheDir() دادهها را در حافظه پنهان برنامه مدیریتشده و ایمن ذخیره کنید. توجه داشته باشید که این حافظه پنهان داخلی ممکن است زمانی که سیستم در فضای ذخیرهسازی موجود کم است پاک شود.
از یک مخزن استفاده کنید
برای یک رویکرد پیچیده تر برای ذخیره سازی، الگوی طراحی مخزن را در نظر بگیرید. این شامل ایجاد یک کلاس سفارشی به نام Repository است که یک انتزاع API را بر روی برخی داده ها یا منابع خاص ارائه می دهد. مخزن ممکن است در ابتدا داده های خود را از منابع مختلف، مانند یک سرویس وب راه دور، واکشی کند، اما در تماس های بعدی، یک نسخه ذخیره شده از داده ها را در اختیار تماس گیرندگان قرار می دهد. این لایه غیرمستقیم به شما این امکان را می دهد که یک استراتژی ذخیره سازی قوی که مختص برنامه شما است ارائه دهید. برای اطلاعات بیشتر در مورد استفاده از الگوی مخزن در برنامه خود، به راهنمای معماری برنامه مراجعه کنید.
محتوا و نمونه کدها در این صفحه مشمول پروانههای توصیفشده در پروانه محتوا هستند. جاوا و OpenJDK علامتهای تجاری یا علامتهای تجاری ثبتشده Oracle و/یا وابستههای آن هستند.
تاریخ آخرین بهروزرسانی 2025-08-27 بهوقت ساعت هماهنگ جهانی.
[[["درک آسان","easyToUnderstand","thumb-up"],["مشکلم را برطرف کرد","solvedMyProblem","thumb-up"],["غیره","otherUp","thumb-up"]],[["اطلاعاتی که نیاز دارم وجود ندارد","missingTheInformationINeed","thumb-down"],["بیشازحد پیچیده/ مراحل بسیار زیاد","tooComplicatedTooManySteps","thumb-down"],["قدیمی","outOfDate","thumb-down"],["مشکل ترجمه","translationIssue","thumb-down"],["مشکل کد / نمونهها","samplesCodeIssue","thumb-down"],["غیره","otherDown","thumb-down"]],["تاریخ آخرین بهروزرسانی 2025-08-27 بهوقت ساعت هماهنگ جهانی."],[],[],null,["Some 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\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\nKotlin \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\nJava \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\nKotlin \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\nJava \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\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)."]]