2014-04-17 31 views
4

我目前正在写一个小应用程序,通过下载last.fm生成的XML文件显示在我的本地酒吧当前播放歌曲。的Android - ION缓存导致

我的问题是:与XML同步联机它没有得到新版本的时候,而是采用先下载XML一遍又一遍。与此同时,在随机浏览器中打开此链接确实会提供正确的结果。可能是缓存或懒惰的下载,我不知道。我也不知道这是否与ION相关。

我目前正在与一些代码,下载前通过该应用清除整个缓存固定这个,还有这个效果很好,但因为我可能会想扩展应用程序,我将不得不寻找另一种方式来解决这个问题。

我的代码:

public class MainActivity extends Activity implements OnClickListener { 

private final static String nonXML = {the url to my xml-file} 

private String resultXml; 

private TextView artistTextView, songTextView, albumTextView; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    artistTextView = (TextView) findViewById(R.id.artistTextView); 
    songTextView = (TextView) findViewById(R.id.songTextView); 
    albumTextView = (TextView) findViewById(R.id.albumTextView); 
    Button mainButton = (Button) findViewById(R.id.mainButton); 

    mainButton.setOnClickListener(this); 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    update(); 
} 

@Override 
public void onClick(View v) { 
    update(); 
} 

private void update() { 
    deleteCache(this); 
    getXML(); 

    XMLToClass convertor = new XMLToClass(); 
    NonPlaylist non = convertor.convert(resultXml); 

    artistTextView.setText(non.getArtist()); 
    songTextView.setText(non.getSong()); 
    albumTextView.setText(non.getAlbum()); 
} 

private void getXML() { 
    try { 
     Ion.with(getBaseContext(), nonXML) 
       .asString() 
       .setCallback(new FutureCallback<String>() { 
        @Override 
        public void onCompleted(Exception e, String result) { 
         resultXml = result; 
        } 
       }).get(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } catch (ExecutionException e) { 
     e.printStackTrace(); 
    } 
} 

public static void deleteCache(Context context) { 
    try { 
     File dir = context.getCacheDir(); 
     if (dir != null && dir.isDirectory()) { 
      deleteDir(dir); 
     } 
    } catch (Exception e) {} 
} 

public static boolean deleteDir(File dir) { 
    if (dir != null && dir.isDirectory()) { 
     String[] children = dir.list(); 
     for (int i = 0; i < children.length; i++) { 
      boolean success = deleteDir(new File(dir, children[i])); 
      if (!success) { 
       return false; 
      } 
     } 
    } 
    return dir.delete(); 
} 
} 

回答

10

离子确实事实上缓存,根据HTTP规范。如果您想忽略缓存,请在构建请求时使用.noCache()方法。

提示:您还可以打开详细日志记录在离子请求,看看什么是引擎盖下发生至于缓存等

.setLogging(“MyTag”,Log.VERBOSE)

+0

奇迹般有效!谢谢! – Daemun

+0

Ion缓存请求需要多长时间?应用程序实例的生命?缓存的大小是否有限制?如何清除缓存? – William

+0

有没有办法清除Ion的缓存? – lahsrah

相关问题