我正在開發一個Android應用程序,其目標是將一些數據發送到服務器。然而,有時候可能沒有wifi連接,所以我想問一下是否可以創建一個緩存來存儲多組數據,比如說3組數據,然後應用程序會在有連接時自動發送這些數據。爲Android應用程序創建緩存
這是我最近把我的DATAS到服務器的方式:我覺得緩存數據是簡單
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();
}
}
所以我可以利用示例代碼來確定是否存在連接,並讓程序等待沒有連接的情況。其實,我想要做的就是像whatsapp,所以當沒有互聯網連接,它會先緩存數據,然後它可以發送,即使我已經返回到主頁 – Conrad 2012-07-31 05:54:49
這實際上是一個不同的問題,你可以使用服務在示例代碼中監聽網絡狀態更改事件。當連接可用時發送數據。即使您返回家中,該服務也將在後臺運行。 – StarPinkER 2012-07-31 07:07:42