我正在开发一个Android应用程序,其目的是将一些数据发送到服务器。但是,有时候可能没有wifi连接,所以我想问一下是否可以创建一个缓存来存储多组数据,比如说3组,然后当连接可用时,app会自动发送这些数据。
以下是我最近将数据发送到服务器的方式:
private class GrabURL extends AsyncTask<String, Void, Void>{
//ArrayList object for storing the string pairs
ArrayList<NameValuePair> nameValuePairs;
public GrabURL() {
//constructor of the class
nameValuePairs = new ArrayList<NameValuePair>();
}
protected void onPreExecute(String key, String value) {
//store the pair of values into the ArrayList
nameValuePairs.add(new BasicNameValuePair(key,value));
}
@Override
protected Void doInBackground(String... urls) {
// TODO Auto-generated method stub
//Operation being executed in another thread
try{
//set up the type of HTTPClient
HttpClient client = new DefaultHttpClient();
//set up the location of the server
HttpPost post = new HttpPost(urls[0]);
//translate form of pairs to UrlEncodedFormEntity
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8);
//set up the entity being sent by post method
post.setEntity(ent);
//execute the url and post the values
//client.execute(post);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
line = EntityUtils.toString(resEntity);
} catch (Exception e) {
//catch the exception
line = "Can't connect to server";
}
return null;
}
protected void onPostExecute(Void unused) {
Toast.makeText(getApplicationContext(), "Value updated", Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:1)
要存储原始内容,您只需使用 SharedPreferences ,一旦网络可用,您就可以检查SharedPreferences中是否存在具有特定密钥的内容。如果你不在持久环境中写入数据(如SharedPreferences,Sqlite,SD卡或内部存储器中的文件等),关闭应用程序将导致数据丢失。
答案 1 :(得分:0)
我认为缓存数据很简单,您可以将其存储在内存中或将它们存储为文件。您可以监听网络状态更改事件,以便在有可用连接时收到通知。
这是Sample Code。
答案 2 :(得分:0)
这可能有助于为对象+图像缓存提供抽象缓存库;