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'.