In android how to programmatically clear web cache without clearing database - android

I m developing an android app in which i'm integrating facebook functionality as suggested in this blog http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/
as i'm able to login first time but after logout i cannot able to login again as webcache get created in my application data....
is there any way which i can use to solve my problem ......is i have use below code as suggested here but it cannot delete delete my webcache...
static int clearCacheFolder(final File dir, final int numDays) {
int deletedFiles = 0;
if (dir != null && dir.isDirectory()) {
try {
for (File child : dir.listFiles()) {
// first delete subdirectories recursively
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child, numDays);
}
// then delete the files and subdirectories in this dir
// only empty directories can be deleted, so subdirs have
// been done first
if (child.lastModified() < new Date().getTime() - numDays
* DateUtils.DAY_IN_MILLIS) {
if (child.delete()) {
deletedFiles++;
}
}
}
} catch (Exception e) {
Log.e("error Tag",
String.format("Failed to clean the cache, error %s",
e.getMessage()));
}
}
return deletedFiles;
}
please do suggest some another way to delete my webcache without deleting my database.....

Related

how to check a html file exist in assets folder

Assets
|-man
| |-myhtml.html
|
|-women
| |-myhtml.html
this is my folder structure some times i need to check the file exist in men some times i need to check the file exist in women what can i do.
try {
fileExist = Arrays.asList(getResources().getAssets().list("")).contains(pathInAssets);
} catch (FileNotFoundException e) {
fileExist = false;
} catch (IOException e) {
e.printStackTrace();
}
this give only the list man and women i cant go inside it and check the existance.
Is their any other way to check this
use below method to get file from assets folder.
i provide code get all .mp4 file and store file into string list.
private List<String> videoList=new ArrayList<>();
private boolean listAssetFiles(String path) {
String [] list;
try {
list = getAssets().list(path);
if (list.length > 0) {
// This is a folder
for (String file : list) {
if (!listAssetFiles(path + "/" + file))
return false;
else {
// This is a file
// TODO: add file name to an array list
if (file.contains(".mp4") || file.contains(".mp3") ) {
videoList.add(file);
}
}
}
}
} catch (IOException e) {
return false;
}
return true;
}
when you call this method pass only ..
listAssetFiles(""); // you can pass your path if is empty then it scan root.
Just open an input stream for the file. As if you were going to read the file.
If you manage to open it the file does exist. Otherwise you get an exception.

android kitkat webview cache issue

One day, My customer says "Webview cache seem to stack data area, not cache area. My device is Optimus G 4.4.2 Kitkat".
Whether cache is really accumulate in the data area, i checked my 4.4.2 device.
so, cache was being really accumulated the data area.
and, it does not delete the following way.
protected void trimCache(Context context) {
try {
dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
children = dir.list();
for (String aChildren : children) {
if (deleteDir(new File(dir, aChildren))) continue;
return false;
}
}
assert dir != null;
return dir.delete();
}
and, Webview.clearCache() and Context.deleteDatabase("") .
I have two Question.
How can i delete cache in the data area?
if i can't delete cache in the data area, How i can turn off android webview cache.
p.s. I'm not native speaker, so my english is not enough.
How can i delete cache in the data area?
You can take a look at this link for further info as to how to delete the cache data. There is a recursive method that, that guy is using.
if i can't delete cache in the data area, How i can turn off android webview cache.
You can try using
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.getSettings().setAppCacheEnabled(false);
But more importantly, just after creating your webview, before loading any pages, you can clear the cache, as mentioned in the documentation here.
mWebView.clearCache(true)
i am using this to clear cache from data.
try {
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (!s.equals("databases") &&!s.equals("lib") && !s.equals("shared_prefs")) {
deleteDir(new File(appDir, s));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}

Delete cached files - WebView Android 4.4+

I managed to delete cached files created by WebView using:
Clearing android cache,
Clear Application cache on exit in android
However for Android 4.4 that solution doesn't work properly, since the files are cached in:
/data/data/com.app.package/app_webview/
instead of:
/data/data/com.app.package/cache/
The above path can be obtained by the official command getCacheDir().
An approach could be hard-coding the path obtained through Get Application Directory
However, is there any [official]/proper solution to address this?
you can use this code
private static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (String aChildren : children) {
boolean success = deleteDir(new File(dir, aChildren));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir != null && dir.delete();
}
void trimCache() {
try {
String pathadmob = this.getFilesDir().getParent() + "/app_webview";
File dir = new File(pathadmob);
if (dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Also, here was generated all admob cache 4.4+, you can use a code to verify how many times the user use the app, and delete the admob cache when the user reached the limit.
Normally, to clear WebView cache, use this WebView API: WebView.clearCache(true);

android dns cache clear

I have created an application which pings some webpage and sends sms in case it fails.
But when the DNS is not working this application is not sending sms because the IP of the webpage ex. www.google.com is saved into the dns cache and my application is still using this ip and as a result i am not notified about the problem.
I have tried the methods below to delete this cache files but no success :
static int clearCacheFolder(final File dir, final int numDays) {
int deletedFiles = 0;
if (dir!= null && dir.isDirectory()) {
try {
for (File child:dir.listFiles()) {
//first delete subdirectories recursively
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child, numDays);
}
//then delete the files and subdirectories in this dir
//only empty directories can be deleted, so subdirs have been done first
//if (child.lastModified() < new Date().getTime() - numDays *DateUtils.DAY_IN_MILLIS) {
if (child.delete()) {
deletedFiles++;
}
//}
}
}
catch(Exception e) {
Log.e(TAG, String.format("Failed to clean the cache, error %s", e.getMessage()));
}
}
return deletedFiles;
}
ublic static void clearCache(final Context context, final int numDays) {
Log.i(TAG, String.format("Starting cache prune, deleting files older than %d days",numDays));
int numDeletedFiles = clearCacheFolder(context.getCacheDir(), numDays);
Log.i(TAG, String.format("Cache pruning completed, %d files deleted", numDeletedFiles));
This code does not clear the application cache. Does anyone knows why ? Please help !
There is also another post in this forum as below :
System.setProperty( "networkaddress.cache.ttl", "0" );
System.setProperty( "networkaddress.cache.negative.ttl", "0" );
I just wanted to know if the above code will help and how can i use it in my android code ? Please let me know !
Thanks

Format SD card in Android

Things should be simple, but as most of the time, in Android, aren't. I need to format the SD card if the user selects the option in my app. Don't ask me why I need to do this if it's already in the OS... not practical but it's a requirement that I need to implement. As you may know, there is an option in Settings \ Storage \ Erase SD Card. I took a look at the froyo source code and it's something like:
final IMountService service =
IMountService.Stub.asInterface(ServiceManager.getService("mount"));
if (service != null) {
new Thread() {
public void run() {
try {
service.formatVolume(Environment.getExternalStorageDirectory().toString());
} catch (Exception e) {
// Intentionally blank - there's nothing we can do here
Log.w("MediaFormat", "Unable to invoke IMountService.formatMedia()");
}
}
}.start();
} else {
Log.w("MediaFormat", "Unable to locate IMountService");
}
It uses android.os.storage.IMountService and android.os.ServiceManager and I don't seem to have access to it. So, as I see it I could recursively search every file and delete it but that would be "not on my taste"... or I could start the screen from Erase SD card to the user.
Any help is more then welcome, as I am stuck.
First of all, I think that you may need to umount .android_secure filesystem before formatting SD card, whatever your approach may be.
Then,
Try including following permissions in your app:
1) MOUNT_FORMAT_FILESYSTEMS - http://developer.android.com/reference/android/Manifest.permission.html#MOUNT_FORMAT_FILESYSTEMS
2) MOUNT_UNMOUNT_FILESYSTEMS - http://developer.android.com/reference/android/Manifest.permission.html#MOUNT_UNMOUNT_FILESYSTEMS
Android Settings app already uses the 2nd permission.
================================================================================
When you perform a build of AOSP or any other distribution code, IMountService.java file gets generated automatically. It contains following function which actually sends formatting commands to vold daemon I guess.:
private static class Proxy implements android.os.storage.IMountService
{
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote)
{
mRemote = remote;
}
public android.os.IBinder asBinder()
{
return mRemote;
}
// **** A LOT OF OTHER CODE IS HERE.....
public int formatVolume(java.lang.String mountPoint) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(mountPoint);
mRemote.transact(Stub.TRANSACTION_formatVolume, _data, _reply, 0);
_reply.readException();
_result = _reply.readInt();
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
}
I can't find again the question here on SO, but It had a working solution. So all credit goes to that guy ;)
public void wipeMemoryCard() {
File deleteMatchingFile = new File(Environment
.getExternalStorageDirectory().toString());
try {
File[] filenames = deleteMatchingFile.listFiles();
if (filenames != null && filenames.length > 0) {
for (File tempFile : filenames) {
if (tempFile.isDirectory()) {
wipeDirectory(tempFile.toString());
tempFile.delete();
} else {
tempFile.delete();
}
}
} else {
deleteMatchingFile.delete();
}
} catch (Exception e) {
Utils.log(e.getMessage());
}
}
private static void wipeDirectory(String name) {
File directoryFile = new File(name);
File[] filenames = directoryFile.listFiles();
if (filenames != null && filenames.length > 0) {
for (File tempFile : filenames) {
if (tempFile.isDirectory()) {
wipeDirectory(tempFile.toString());
tempFile.delete();
} else {
tempFile.delete();
}
}
} else {
directoryFile.delete();
}
}

Categories

Resources