Android enables offline caching
In a world where the Internet cannot be missed, [Android offline cache][6] will address the use of apps in environments where there is no Internet, currently using this technology has NetEase news, God Horse news, the main advantage is: to achieve offline browsing, in the offline state, browse news (can also be implemented with H5) reduce server pressure, reduce the concurrency of the server to improve the response speed of the client
It is implemented in the following ways: Save to local file store , save to SQLite database store to local file store
Save network data locally: First you need to write a way to save your network data locally.
public static Boolean Saveobject (Serializable ser, String file) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = appcontext.getinstance (). Openfileoutput (file, Appcontext.getinstance (). Mode_private);
Oos = new ObjectOutputStream (FOS);
Oos.writeobject (Ser);
Oos.flush ();
return true;
} catch (Exception e) {
e.printstacktrace ();
return false;
} Finally {
try {
oos.close ();
} catch (Exception e) {
}
try {
fos.close ();
} catch ( Exception e) {
}
}
}
Openfileoutput can directly obtain a file path that is associated with an application (under/data/data//files), and then use the Java The ObjectOutputStream in IO writes the serialized object (WriteObject) to the resulting file, and you can see that there are two key approaches to the implementation: Openfileoutput, WriteObject and the two key objects that call them context and objectoutputstream.
This is the relationship between storing a serialized object locally and saving the network data with our offline cache.
Because most of the data retrieved on the Web can be converted to string strings, the data returned by the server is typically a JSON-formatted string.
With the above Saveobject method we can save the data locally, in order to be able to remove the file we have to think about how to name the saved file, if it is a simple article of data, we can directly name the file name is the ID of this article, because ID is unique, In order to not conflict with other data as much as possible, you can add a prefix before this ID, such as this article is the Java column we can do so arc_java_id. If it is a list of articles we can name: Article category _ pagination page number, in short, the principle of naming is able to and other offline data differences, there is uniqueness. Why not use URLs as file names? URLs are definitely unique, but URLs do not necessarily conform to the naming conventions for files.
to read local cached data:
Reads the cache according to the file name while reading the cache, the following ReadObject method implements the read cache data based on the filename.
/**
* Read Object
* *
@param file
* @return
* @throws ioexception/public
static Serializable ReadObject (String file) {
FileInputStream FIS = null;
ObjectInputStream ois = null;
try {
FIS = appcontext.getinstance (). openfileinput (file);
OIS = new ObjectInputStream (FIS);
Return (Serializable) ois.readobject ();
} catch (FileNotFoundException e) {
} catch (Exception e) {
e.printstacktrace ();
} finally {
try {
ois.close ();
} catch (Exception e) {
}
try {
fis.close ();
} catch (Exception e) {
}
} return
null;< c27/>}
The following code demonstrates how to store and read network data using the above knowledge
String key = Codelist_ + mcategory.getvalue () + _ + + page;
String result =;
Cache
if (httputil.isnetworkconnected ()) {Result
= Httputil.http_get (appcontext.getinstance (), URL);
Httputil.saveobject (result, key);
result = (String) httputil.readobject (key);
} else {result
= (String) httputil.readobject (key);
if (result = = NULL) result
= Erro;
}
When the network is unblocked, get the data from the server (Httputil.http_get (appcontext.getinstance (), URL), At the same time, the data is saved locally (httputil.saveobject), and when the network is unavailable, the cached data is read directly from the local and does not interact with the server. Development:
Sometimes we have the requirement that when a user reads the same data source at a specified interval, it is fetched locally, over this time interval from the network, to save the user's traffic while avoiding the interface latency that results from each time the data is fetched from the network.
Here's how to determine if you need to refresh the server data based on the time interval, true means no, false indicates a need
public static Boolean iscachedatafailure (String cachefile) {
Boolean failure = false;
File data = Appcontext.getinstance (). Getfilestreampath (cachefile);
if (data.exists ()
&& (System.currenttimemillis ()-data.lastmodified ()) > Cache_time)
failure = true;
else if (!data.exists ())
failure = true;
return failure;
}
Compare the current time to the file's modification time, Cache_time is a fixed value (milliseconds) and you can replace it with any int type.
Full application code:
String key = Codelist_ + mcategory.getvalue () + _ + + page;
String result =;
Cache
if (httputil.isnetworkconnected () && httputil.iscachedatafailure (key) {Result
= Httputil.http_get (appcontext.getinstance (), URL);
Httputil.saveobject (result, key);
result = (String) httputil.readobject (key);
} else {result
= (String) httputil.readobject (key);
if (result = = NULL) result
= Erro;
}
Perfect function:
The above steps are sufficient for general applications, but in the case of high requirements, we have to consider over time, cached data will be more and more, so we need to increase the ability to delete expired cache, the principle is to set a threshold, when saving the cache, to determine whether the current total cache is greater than the threshold, If yes, delete the earlier cache, if you save the time attribute.
This implementation is a bit complicated, you can consider a more simple scheme, periodic check (or the user every time the program) cache total, when greater than the threshold, prompting the user to delete voluntarily. Save to SQLite database store
Implementation Method : This method is after downloading the data file, the file related information such as URL, path, download time, expiration time and so on to the database, of course, I personally suggest that the URL as a unique identification. The next time you download the query from the database based on the URL, if the query to the current time does not expire, read the local file based on the path, so as to achieve the effect of caching.
Advantages: This method can flexibly store the properties of the file, which provides a great extensibility, can provide some support for other functions.
Disadvantages: from the operation of the need to create a database, each query the database, if the expiration also needs to update the database, cleaning up the cache also need to delete the database data, slightly more trouble, and the database operation is not easy and prone to a series of performance, ANR problems, pointer errors, to achieve the time to Concrete implementation, but also just add a tool class or method of things. At the same time, the cached database is stored in the/data/data//databases/directory, is occupied by memory space, if the cache accumulation, easy to waste memory, need to clean up the cache in time.
Pros and cons, developers according to the user's own operating habits and use of the situation to choose the appropriate way.