Android - ION缓存结果

Den*_*nie 4 android caching last.fm android-ion

我目前正在编写一个小应用程序,通过下载last.fm生成的XML文件来显示当前在我的本地酒吧中播放的歌曲.

我遇到的问题如下:当与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();
}
}
Run Code Online (Sandbox Code Playgroud)

kou*_*ush 10

根据http规范,Ion确实可以缓存.如果要忽略缓存,请在构建请求时使用.noCache()方法.

提示:您还可以打开离线请求中的详细日志记录,以查看有关缓存等问题的详细信息.

.setLogging("MyTag",Log.VERBOSE)

  • 离子缓存根据http响应上的缓存头.可以使用以下命令清除缓存:Ion.getDefault(getContext()).configure().getResponseCache().clear(); (2认同)