- Android Context getCacheDir()
- Introduction
- Syntax
- Example
- Displaying Cache data or Offline mode support in android application
- MindOrks
- Android Tutorial: Android External Storage
- 1 What is Android external storage?
- 2 Why external storage?
- 3 Android external storage APIs Overview
- 3.1 Environment.getExternalStorageDirectory()
- 3.2 Context.getExternalFilesDir(String type)
- 3.3 Context.getExternalCacheDir()
- 3.4 Environment.getExternalStoragePublicDirectory(String type)
- 4 How to Use Android external storage
- 5 Android external storage example
- 5.1 Add WRITE_EXTERNAL_STORAGE permission
- 5.2 Helper method to check external storage state
- 5.3 Helper method to write file
- 5.4 Listen button clicking
- Зачем использовать getCacheDir() на Android
- 2 ответов
- Different ways to get Context in Android
- The “this” Keyword
- Get current activity context : View.getContext()
- Get App-level context : getApplicationContext()
- Get Original context : getBaseContext()
- Get Context from Fragment : getContext()
- Get parent Activity : getActivity()
- Non-nullable Context : requireContext() and requireActivity()
Android Context getCacheDir()
Android Context getCacheDir() Returns the absolute path to the application specific cache directory on the filesystem.
Introduction
Returns the absolute path to the application specific cache directory on the filesystem.
The system will automatically delete files in this directory as disk space is needed elsewhere on the device.
The system will always delete older files first, as reported by File#lastModified().
If desired, you can exert more control over how files are deleted using (StorageManager# setCacheBehaviorGroup(File, boolean)) and (StorageManager# setCacheBehaviorTombstone(File, boolean)).
Apps are strongly encouraged to keep their usage of cache space below the quota returned by StorageManager#getCacheQuotaBytes(java.util.UUID).
If your app goes above this quota, your cached files will be some of the first to be deleted when additional disk space is needed.
Conversely, if your app stays under this quota, your cached files will be some of the last to be deleted when additional disk space is needed.
Note that your cache quota will change over time depending on how frequently the user interacts with your app, and depending on how much system-wide disk space is used.
The returned path may change over time if the calling app is moved to an adopted storage device, so only relative paths should be persisted.
Apps require no extra permissions to read or write to the returned path, since this path lives in their private storage.
Syntax
The method getCacheDir() from Context is declared as:
The method getCacheDir() returns The path of the directory holding application cache files.
Example
The following code shows how to use Java Context getCacheDir()
Источник
Displaying Cache data or Offline mode support in android application
Problems without caching
1. Fetching data over a network connection is an expensive operation. Sometimes due to poor network connectivity, it takes a lot of time to display result( which is a bad experience in terms of mobile application).
2. Sometimes requirement may come with offline support or to display previously fetched response when there is no internet connectivity.
Thanks to Caching mechanism. We can solve the above requirements if we cache some data.
In my project, I have used the dagger, so I have written all the code for caching in ApiModule class. If you want to skip then directly go to below link
How to enable cache
1. define cache memory size
2. Create a cache object ( provide application context )
Provide this cache object in OkHttpClient
Now we will create 2 interceptors ( onlineInterceptor and offlineInterceptor). Interceptors are a powerful mechanism that can monitor, rewrite, and retry calls.
OnlineInterceptor which will be used when the device is connected to the network
OfflineInterceptor which will be used when the device is not connected to the network
Now its time to add cache interceptor to OkHttpClient.
Finally, add OkHttpClient to Retrofit
Using this retrofit instance, we can make an API call and the caching mechanism will work.
Few points to remember
Soon I will post more articles on android, core java.
till then happy learning… 🙂
MindOrks
Our community publishes stories worth reading on Android…
Источник
Android Tutorial: Android External Storage
Tutorial about how to use Android external storage.
1 What is Android external storage?
What Android «external storage» means is described in Android SDK Document:
Every Android-compatible device supports a shared «external storage» that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non-removable) storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.
So don’t be confused by the word «external» here. External storage can better be thought as media or shared storage. Traditionally this is an removable SD (Secure Digital) card, but it may also be implemented as built-in non-removable storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
2 Why external storage?
Android has already provided efficient internal storage for application, but still there is much need for external storage under certain circumstance.
- Need more memory or disk space to save big files;
- Let data saved or generated in your application be accessed by other applications;
- Some saved data should not be deleted although your application is uninstalled. For example, pictures, videos downloaded by your application.
3 Android external storage APIs Overview
Main APIs for Android external storage.
- Environment.getExternalStorageDirectory() : return the primary external storage root directory.
- Context.getExternalFilesDir(String type) : return the absolute path of the directory on the primary external storage where the application can place its own files.
- Context.getExternalCacheDir() | return reference to your application specific path of cache directory on external storage.
- Environment.getExternalStoragePublicDirectory(String type) | return public external storage directory for saving files of a particular type.
Following figure gives an overview of Android external storage APIs.
3.1 Environment.getExternalStorageDirectory()
Environment.getExternalStorageDirectory() returns top-level directory of the primary external storage.
If device has multiple external storage directories, returned directory represents the primary external storage that the user will interact with. There is also APIs available for accessing secondary storage or getting external storage directories list.
- Context.getExternalFilesDirs(String type)
- Context.getExternalCacheDirs()
- Context.getExternalMediaDirs()
It is noticed that the returned directory of Environment.getExternalStorageDirectory() is the top-level directory of the external storage. You application should avoid placing files directly under this top-level directory. If your application needs save public or shared data, you’d better use directory returned by getExternalStoragePublicDirectory(String type) ; on the other hand, if your application only needs to store its own internal data on external storage, you’d better consider using getExternalFilesDir(String) or getExternalCacheDir() instead.
3.2 Context.getExternalFilesDir(String type)
Returns the absolute path to the directory on the primary shared or external storage device where the application can place persistent files it owns. These files are internal to the application.
The returned directory is owned by the application and its contents will be deleted when the application is uninstalled.
The type parameter can be null or one of the following constant value.
- Environment.DIRECTORY_MUSIC
- Environment.DIRECTORY_PODCASTS
- Environment.DIRECTORY_RINGTONES
- Environment.DIRECTORY_ALARMS
- Environment.DIRECTORY_NOTIFICATIONS
- Environment.DIRECTORY_PICTURES
- Environment.DIRECTORY_MOVIES
If the type parameter is null , the returned path will be the root the files directory; otherwise, will be a sub directory of the given type.
3.3 Context.getExternalCacheDir()
Returns absolute path to application-specific directory on the primary shared or external storage device where the application can place cache files it owns.
Cached files under returned directory will be deleted when the application is uninstalled. Android platform does not always monitor the space available in shared storage, and thus may not automatically delete these cached files. Your application itself should always manage the maximum space used in this location.
3.4 Environment.getExternalStoragePublicDirectory(String type)
Get a top-level shared or external storage directory for placing files of a particular type.
The type parameter CAN NOT be null , should be one of the following constant value.
- Environment.DIRECTORY_MUSIC
- Environment.DIRECTORY_PODCASTS
- Environment.DIRECTORY_RINGTONES
- Environment.DIRECTORY_ALARMS
- Environment.DIRECTORY_NOTIFICATIONS
- Environment.DIRECTORY_PICTURES
- Environment.DIRECTORY_MOVIES
Because this returned directory is public and is for shared files, you application should be careful and avoid erasing any files here.
4 How to Use Android external storage
External storage of Android device may not always be available, for example:
- external storage may not be accessible if it has been mounted by users on their computer;
- external storage has been removed from device.
So the first step is to check state of the external storage. External storage state can be checked using Environment.getExternalStorageState(File path) . More details can refer to Android Tutorial: Check SD Card Status.
The second step is to add android.permission.READ_EXTERNAL_STORAGE or android.permission.WRITE_EXTERNAL_STORAGE permission to your application.
Note: From Android 6.0+, application has to ask user for a permission one-by-one at runtime instead of being granted any permission at installation time.
The third step is to get File object reference of external storage directory.
Lastly, write or read data using common java.io APIs with the directory File object.
5 Android external storage example
There are two main features in this simple demo:
- Show various external storage full path using Toast ;
- Try to write demo file to external storage;
Main UI of the demo looks like screenshot below.
5.1 Add WRITE_EXTERNAL_STORAGE permission
Add android.permission.WRITE_EXTERNAL_STORAGE permission to AndroidManifest.xml file of your Android application project.
5.2 Helper method to check external storage state
Create a helper method in Activity class to check external storage state.
5.3 Helper method to write file
Create a common helper method to write string to a file.
5.4 Listen button clicking
Lastly, implement View.OnClickListener interface in the demo Activity.
You can check the saved file via file explore of Android Device Monitor (DDMS) in Android Studio or Eclipse.
Источник
Зачем использовать getCacheDir() на Android
Android может автоматически удалять файлы в CacheDir, как только система получает мало памяти. Но документы говорят, что мы не должны полагаться на очистку этого кэша системой и, следовательно, писать дополнительный код для опроса и удаления.
Если это так, почему следует выбрать getCacheDir() над getFilesDir() ? Оба они находятся в памяти, и последний предлагает разработчику больше возможностей с точки зрения того, что очищать и когда.
2 ответов
Android может автоматически удалять файлы в CacheDir, как только система получает мало памяти.
правильно. Сторонние приложения также могут удалять файлы из каталогов кэша приложений. И, как отмечает zapl, пользователь может вручную очистить кэш приложения от настроек.
но документы говорят, что мы не должны полагаться на систему очистки этого кэша, и, следовательно, написать дополнительный код для опроса и удаления.
если это так, почему нужно выбрать getCacheDir () над getFileDir ()?
потому что ОС, сторонние приложения и пользователь can очистить кэш. Однако только потому, что эти вещи can очистить кэш не означает, что они автоматически будет очистите кэш, и поэтому вам нужно время от времени убирать свой кэш самостоятельно. Точно так же, пока твоя мать can очистить ваша комната, это вообще хорошая идея, если вы убираете свою комнату самостоятельно, если вы не хотите, чтобы вас ударили метлой.
и последний предлагает больше власти разработчику с точки зрения того, что очистить и когда.
нет, это не так. getCacheDir() возвращает
getCacheDir() возвращает путь к файлам кэша, тогда как getFilesDir() возвращает путь к файлам, созданным и сохраненным во внутреннем хранилище приложения. Внутреннее хранилище является постоянным: оно не может быть удалено системой.
Источник
Different ways to get Context in Android
Context is one of the important and most used property. You need Context to perform a lot of things on Android. Be is displaying a toast or Accessing database, you use context a lot while building Android app.
Context is property, well, which can give you the context of whats happening on the Screen/Activity it belongs to. It contains information about what Views are there, How they are laid out etc.
So, it is important to know different types of Context and methods you can call to get context. Lets get started.
The “this” Keyword
The this keyword in general sense refers to current class instance. So, when use “this” keyword inside an Activity, it refers to that Activity instance. And as Activity is subclass of “Context”, you will get context of that activity.
If you are not directly inside Activity, for example inside an OnClickListener, you can get the current context by referencing with Activity name like MainActivity.this (Java) or this@MainActivity (Kotlin)
Get current activity context : View.getContext()
This method can be called on a View like textView.getContext() . This will give the context of activity in which the view is currently hosted in.
Get App-level context : getApplicationContext()
If you need to access resources which are out of scope of specific activity, like when accessing SharedPreferences, displaying Toast message etc. you can use this.
So unlike activity context, which will be destroyed when close an activity, Application Context the application wide context which won’t get destroyed until you completely close application.
You can directly access application context by calling getApplicationContext() or by calling on activity context like context.getApplicationContext()
Get Original context : getBaseContext()
This method is only useful when you are using ContextWrapper. You can get the original context which was wrapped by ContextWrapper by calling contextWrapper.getBaseContext()
( ContextWrapper is a wrapper class, using which you can override any method of Context, while still retaining the original context)
Get Context from Fragment : getContext()
When you call getContext() from an Fragment, you will get the context of the activity in which that fragment is hosted in.
Get parent Activity : getActivity()
You can get the parent activity from a Fragment by calling getActivity() .
💡Difference : Both getContext() and getActivity() are not much different in most cases, when you just need a context as both will get Parent activity context. Except for some cases, for example when using ContextWrapper, getContext() and getActivity() can point to different contexts.
Non-nullable Context : requireContext() and requireActivity()
These methods are same but “NotNull” versions of getContext() and getActivity() respectively. Usually, if a fragment is detached from Activity, you will get “null” value when you call getContext() or getActivity() . So even when you are sure the context won’t be null, you still have to add null checks (especially in Kotlin) because they return Nullable type.
But requireContext() and requireActivity() will throw IllegalStateException instead of returning null, if there is no context.
These methods are mainly useful when you using Kotlin and you need a Non-Nullable Context. So using these methods instead, is matter of personal preference.
So, did you learn something new? If you did, please clap and share the post. 😄
Источник