在android中使用缓存和脱机存储

这篇文章主要介绍了在android中使用缓存和脱机存储,缓存可以加速你的应用程序,即使在网络不可用时,用户能够更加流畅地使用你的应用程序使用缓存是相当简单的,需要一个单一的代码行,下面来看看文章的详细内容

1、在android中使用缓存和脱机存储

  缓存可以加速你的应用程序,即使在网络不可用时,用户能够更加流畅地使用你的应用程序使用缓存是相当简单的,需要一个单一的代码行。

导入 import com.shephertz.app42.paas.sdk.android.App42CacheManager即可,同时需要设置缓存策略。

  •  Policy.CACHE_FIRSTSetting 将激活所有数据的读操作首先从缓存中获取,如果缓存中数据可用且没有失效,就直接从缓存返回,否则进行网络请求这个数据,同时将这个数据更新或加入缓存中,你可以通过API设置缓存失效期,缺省是1一个小时。
  • Policy.NETWORK_FIRST 首先从网络获取数据,然后更新缓存。如果网络不可用,数据就从缓存中取出
  • cache.Policy.NOCACHEBy 这是App42 SDK默认,不使用任何缓存,总是仅从网络读数据。

设置缓存策略如下:

 App42CacheManager.setPolicy(Policy.CACHE_FIRST); 

缓存失效期:

 App42CacheManager.setExpiryInMinutes(); 

案例代码如下:

 UserService userService = App42API.buildUserService(); String userName = "Nick"; userService.getUser(userName,new App42CallBack() { public void onSuccess(Object response) { User user = (User)response; if(user.isFromCache()){ //Response coming from Cache System.out.println("userName is " + user.getUserName()); System.out.println("emailId is " + user.getEmail()); System.out.println("is from cache is " + user.isFromCache()); } else{ //Response From Server System.out.println("userName is " + user.getUserName()); System.out.println("emailId is " + user.getEmail()); } } public void onException(Exception ex) { System.out.println("Exception Message"+ex.getMessage()); } });

If Response is from cache you will get isFromCache flag to true in the response so you can identify that data is real time or data is coming from cache.

如果响应来自缓存,你在响应中通过isFromCache标识为true,这样你能分辨数据是实时的还是来自缓存的。

下面是需要在manifest.xml加入的:

   

2、Offline storage离线存储

  离线存储允许你在本地网络的情况下不可用提交数据,当网络可用时,服务器会同步。这在许多情况下是非常有用的,例如如果你的用户玩游戏,并取得了一些特定级别的完成。然而,在发送成绩时,网络断了,那么他的得分可能会丢失,使用脱机缓存会在本地网络无法获得情况下,保存他的得分,并将于稍后网络恢复可用时与同步服务器的。

使用脱机:

 App42API.setofflineStorage(true); 

案例代码:

 //Set Offline Storage to True App42API.setofflineStorage(true); String gameName = ""; String userName = "Nick"; BigDecimal gameScore = new BigDecimal(3500); scoreBoardService.saveUserScore(gameName, userName, gameScore,new App42CallBack() { public void onSuccess(Object response) { Game game = (Game)response; if(game.isOfflineSync()) {     //Request is saved in cache System.out.println("Information is Stored in cache, will send to App42 when network is available"); } else { //Response Received From Server and is Succeseful System.out.println("Server Response : " + game); } } public void onException(Exception ex) { System.out.println("Exception Message"+ex.getMessage()); } }); 

到此这篇关于在android中使用缓存和脱机存储的文章就介绍到这了,更多相关android使用缓存和脱机存储内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是在android中使用缓存和脱机存储的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 移动