I am beginner to Android development. There are several screens in my app and I can navigate back and forth between these screen using "backstack" feature. As I traverse through the app in depth, the memory usage of app is increasing. Sometimes it reaches up to 100 MB..!! It causes app to restart.
As I understand, below may be, possible reasons behind memory overuse:
1) App makes heavy use of images.
2) Backstacking is implemented. (There is only once activity used and other are fragments)
3) There is one background service running continuously for that app.
I am not sure whether these are the actual reasons. Please help me to find out the reasons. Any tips regarding memory overuse problem? One more question, What should be the ideal memory usage of Android app?
call these two method in your app it will delete all cache of images from android data and ur app will not crashed from memory issue
//this is for clear cache folder in android -> data folder which generate by gallry lazy loading
public static void trimCache(Context context) {
try {
// File dir = context.getCacheDir();
File dir = context.getExternalCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
System.out.println("delete cache folderrrrrrrrrr");
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static void trimCacheinternal(Context context) {
try {
File dir = context.getCacheDir();
// File dir = context.getExternalCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
System.out.println("delete cache folderrrrrrrrrr");
}
} catch (Exception e) {
// TODO: handle exception
}
}
Related
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();
}
I am currently writing an android app that logs the accelerometer. (its a test app at the moment so i can prototype an algorithm.
To write out a list of SensorEventStore's (which is just a way of storing the data from a SensorEvent) to the SD card from a 30 minute recording, locks up the GUI for about 20 - 30 seconds while writing the file.
I am using the following code to write out the file to the SD card.
#Override
public void onMessage(Messages message, Object param[]) {
if(message == IDigest.Messages.SaveData) {
File folder = (File) param[0];
File accFileAll = new File(folder, startTime + "_all.acc");
FileWriter accFileWriterAll;
try {
accFileWriterAll = new FileWriter(accFileAll);
} catch (IOException e) {
accFileWriterAll = null;
}
for(Iterator<SensorEventStore> i=eventList.iterator(); i.hasNext();) {
SensorEventStore e = i.next();
if(accFileWriterAll != null) {
try {
accFileWriterAll.write(
String.format(
"%d,%d,%f,%f,%f\r\n",
e.timestamp,
e.accuracy,
e.values[0],
e.values[1],
e.values[2]
)
);
accFileWriterAll.flush();
} catch (IOException ex) {
}
}
}
new SingleMediaScanner(RunBuddyApplication.Context, accFileAll);
}
}
Can anyone give me any pointers to make this not lock up the UI, or not have to take the amount of time it currently takes to write out the file.
Firstly you should try to do this in the background. The AsyncTask is fairly well suited for the task.
Other than that, you should remove the flush() statement, and probperly close() your file writer. The flush causes the data to be written to disk in rather small portions, which is really slow. If you leave the filewriter to its own flushing, it will determine a buffer size on its own. When you properly close the FileWriter, the remaining data should be written to disk as well.
Also, you could take a look at "Try with resources" for your filewriter, but that is optional.
I'm writing an application using libgdx and am having a weird issue.
When the game loads, it works well.
The moment you exit the game, and load it again - the graphics are all scrambled (ie - the textures its loading are swapped with other textures, so I might have the texture for the ground replaced with the texture for the main character...).
Clearing the game from the history (and I'm assuming from the cache?) means the game loads perfectly on next time.
So is there a way to tell Android (from the configuration I'm assuming) to not cache the application when I 'close' it?
Using these lines in your activity:-
this.finish();
Process.killProcess( Process.myPid() );
will kill your whole application (assuming its running in a single process) it will also free any associated memory.
This may help in game to load perfectly next time at application will be killed completely.
You can use the following code to remove the catch for your application, Call it from onDestroy() of your activity from where you are going to exit from the application
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();
}
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);
I would like to know about how to delete a folder once user select uninstall button for my application.
I want it by programmatically is there any chance to do it...
If so let me know possible solution for it.
thanks in advance.
If you created any folders on a device's external storage... there is no way for you to call code when the user uninstalls your app. Certain things are removed automatically (databases, anything written to Internal Storage), but not folders on external storage.
EDIT - As pointed out by Stephan, if you are targeting API Level 8 or higher, you can use Context.getExternalFilesDir() for your external files and those will be removed on uninstall.
Here is an idea. If you are concerned about the fact that the files that are not deleted during an uninstall will be messing up the user onboarding process when he later re-installs your app as in this question then you could simply ensure that all data is deleted at the moment your app is reinstalled (or simply installed for that matter). It's a "if Mohammed does not go to the mountain, the mountain will go to Mohammed" kind of hack. Obviously you would have to set a flag in shared preferences so the process of deleting the content of ExternalStorageDir is only performed once before the users very FIRST interaction with your app here is some sample code:
SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);
boolean isFirstInteraction = sharedPreferences.getBoolean("isFirstUsage", true);
if(isFirstInteraction){
trimCache(this);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putBoolean("isFirstUsage",false);
editor.apply();
}
//delete files from external files dir
public static void trimStorage(Context context) {
try {
File dir = context.getExternalFilesDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
e.printStackTrace();
}
}
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) {
Log.d("deletion","failed at "+children[i]);
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}