私がやりたいことは、アプリケーションの終了時にアプリケーションのキャッシュ メモリをクリアすることです。
このタスクは、この手順で手動で実行できます。
< アプリ --> アプリの管理 --> 「マイアプリ」 --> キャッシュの消去 >>
しかし、アプリケーションの終了時にプログラミングしてこのタスクを実行したい..助けてください..
前もって感謝します..
これを試してみてください -
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle *) {
super.onCreate(*);
setContentView(R.layout.main);
}
@Override
protected void onStop(){
super.onStop();
}
//Fires after the OnStop() state
@Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
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;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
}
これらのリンクを参照してください -
アプリケーションデータをクリアするには、この方法をお試しください。お役に立てると思います。
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();
}
明確にするために、 trimCacheは静的メソッドであるため、(メモリリークを回避するために)ActivityコンテキストではなくtrimCacheにApplicationコンテキストを渡す必要があることを除いて、答えは適切に機能します。
@Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(getApplicationContext()); //if trimCache is static
} catch (Exception e) {
e.printStackTrace();
}
}
ただし、それ以外の場合は、trimCacheを非静的にすることができ、Context を渡す必要はありません。
public void trimCache() {
try {
File dir = getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}