Programmatically clear PhoneGap/Cordova app's cache on Android to simulate a fresh install?

android, cordova, java, jquery

Solution

I wasn't able to force android to reload new versions of:

super.loadUrl("file:///android_asset/www/index.html");

between calls, so I first borrowed your code which worked well enough except that all data that my application was writing was deleted as well.

A quick and simple fix is to change the URL of the file above:

super.loadUrl("file:///android_asset/www/index.html?1");

And change the number behind the ? with each load. Eventually I added:

import java.util.Random;

public class MainActivity extends DroidGap {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Random generator = new Random();
        int r = generator.nextInt();
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html?" + r);
    }
}

Now each time I rebuild the app it actually refreshes the cached version of the html file.

I'd very much like to know how to force loadUrl into a refresh from within the app itself, or to force it on reload.

Problem

This is related to my previous question of 'How can I clear my app's localStorage on my Android emulator each time I install it?'. It also builds on 'How can I clear the Android app cache?' and 'How to programatically clear application data?'. None of the above questions give a straightforward answer that is applicable to Android PhoneGap/Cordova applications. This blog post by Igor Hrupin covers the situation in the context of a native Android app, so this question extends that to cover Cordova. I will post an answer myself, but I am a total Java noob, so please edit to improve.

Original source

Related problems