2012-07-31 100 views
1

我正在开发一个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(); 
    } 
} 

回答

0

,可以将其存储在内存中或将它们存储为文件。您可以监听网络状态更改事件,以在有可用连接时收到通知。

这是Sample Code

+0

所以我可以利用示例代码来确定是否存在连接,并让程序等待没有连接的情况。其实,我想要做的就是像whatsapp,所以当没有互联网连接,它会先缓存数据,然后它可以发送,即使我已经返回到主页 – Conrad 2012-07-31 05:54:49

+0

这实际上是一个不同的问题,你可以使用服务在示例代码中监听网络状态更改事件。当连接可用时发送数据。即使您返回家中,该服务也将在后台运行。 – StarPinkER 2012-07-31 07:07:42

1

要保存原始的东西,你可以简单地使用SharedPreferences,并尽快网络可用,您可以检查是否有什么特定的键在SharedPreferences存在。如果你不把数据写入持久化环境(如SharedPreferences,Sqlite,SD卡内部文件或内部存储等),关闭应用程序将导致数据丢失。