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

25,100

Solution 1

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.

Solution 2

just saw this one. It can be done with one line. I am not sure if this is what you want but it serves my purpose which is clearing the cache on startup

https://coderwall.com/p/aj79eg

super.clearCache(); // just add This Line
super.loadUrl("file:///android_asset/www/index.html");

Solution 3

This answer borrows a lot of code from this blog post by Igor Hrupin.

Your Project > src > [com/org/whatever].[YourNameSpace].[ActivityNameHere] > [ActivityNameHere].java should look approximately like this for a normal PhoneGap app.

package [com/org/whatever].[YourNameSpace].[ActivityNameHere];

import org.apache.cordova.*;
import android.os.Bundle;

public class [ActivityNameHere] extends DroidGap {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html");
    }    
}

What we do is change it to look like the following code. Unchanged lines are commented out for clarity, but should be uncommented when implemented.

Please remember to replace [com/org/whatever], [YourNameSpace], and the multiple [ActivityNameHere] placeholders with your own values.

// package [com/org/whatever].[YourNameSpace].[ActivityNameHere];

// import org.apache.cordova.DroidGap;
// import android.os.Bundle;

   import java.io.File;
   import android.util.Log;

// public class [ActivityNameHere] extends DroidGap {

       private static [ActivityNameHere] instance;

    // @Override
    // public void onCreate(Bundle savedInstanceState) {

           instance = this;
           [ActivityNameHere].getInstance().clearApplicationData();

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

   public static [ActivityNameHere] getInstance() {
       return instance;
   }

   public void clearApplicationData() {
       File cache = getCacheDir();
       File appDir = new File(cache.getParent());
       if (appDir.exists()) {
           String[] children = appDir.list();
           for (String s : children) {
               if (!s.equals("lib")) {
                   deleteDir(new File(appDir, s));
                   Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
           }
       }
       }
   }

   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();
   }

// }

As stated in my question, I have no Java skills, so I hacked this together from what I could find and it seems to work. Please edit accordingly - I think this is something that should be available for people to effectively copy & paste when they need it, as the whole point of PhoneGap on Android is to abstract the developer from Java (which, for the record, I will get into learning once my current project is finished).

The code appears to work, at least in my case. It would be nice to add in -

(1) The ability to call this function from JS, along these lines.

and

(2) The choice to clear the cache only the first time the app is run, so you can simulate the app being 'force closed'.

Share:
25,100
Jasper Mogg
Author by

Jasper Mogg

I'm currently a medical student in Newcastle, UK. This doesn't stop me being interested in the machines we live our lives on, in, around and with. I love the feeling of watching a machine perform - in a second - a set of tasks which would take a human being hours, days or weeks. I'm enjoying the power which springs from speaking their language. I also like sharing ideas and being a source of information to others, as well as learning from anyone who can teach me. Finally, the idea of open source is important to me and I hope to one day be able to contribute to the projects that I use on a daily basis. Android here I come ;-) Not that anyone'll ever read this!!

Updated on November 29, 2020

Comments

  • Jasper Mogg
    Jasper Mogg over 3 years

    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.

  • Jasper Mogg
    Jasper Mogg over 11 years
    Me too - that's what I wanted when I posted this. Your answer improves on mine though, so have an accept! :-)
  • Jeroenv3
    Jeroenv3 almost 10 years
    What version of cordova does that work in? Make sure clearCache() doesn't wipe out anything you may have stored in localstorage, that's what it did at the time (in cordova 2.0)
  • Binod Singh
    Binod Singh over 9 years
    This is not working either. I am testing in Kitkat and cordova is 3.6