프로그래밍 방식으로 Android 애플리케이션의 캐시 지우기
프로그래밍 방식으로 Android 응용 프로그램에서 캐시를 지우는 올바른 방법은 무엇입니까? 나는 이미 다음 코드를 사용하고 작동하지 않습니다.
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
clearApplicationData();
}
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("EEEEEERRRRRRROOOOOOORRRR", "**************** 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();
}
자신의 응용 프로그램의 삭제 캐시를 소유하고 캐시 디렉토리를 삭제하면됩니다!
public static void deleteCache(Context context) {
try {
File dir = context.getCacheDir();
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) {
return false;
}
}
return dir.delete();
} else if(dir!= null && dir.isFile()) {
return dir.delete();
} else {
return false;
}
}
Kotlin에는 한 줄짜리
context.cacheDir.deleteRecursively()
dhams의 대답은 삭제하지만 (한 번 편집 한 후) 코드의 많은 편집에서 알 수있는 디렉터리 (하위 디렉터리 포함)를 직접 포함하고 강력한 코드를 작성하는 것은 어렵습니다. 따라서 Apache Commons IO 또는 수행하는 다른 API를 사용하는 것이 좋습니다.
import org.apache.commons.io.FileUtils;
...
// Delete local cache dir (ignoring any errors):
FileUtils.deleteQuietly(context.getCacheDir());
추신 : 사용하는 경우 context.getExternalCacheDir ()에서 반환 한 디렉토리도 삭제하십시오.
Apache Commons IO를 사용하는 경우 build.gradle
다음 dependencies
부분을 파일에 추가하십시오 .
compile 'commons-io:commons-io:2.4'
나는 당신이 clearApplicationData()
전에 배치해야 할 생각 합니다
super.OnDestroy().
앱이 종료되면 어떤 방법도 처리 할 수 없습니다.
잘 모르겠지만이 코드도 뿌렸습니다. 이 대구는 더 빨리 작동하고 내 마음에도 간단합니다. 앱 캐시 디렉토리를 가져오고 디렉토리의 모든 파일을 삭제하십시오.
public boolean clearCache() {
try {
// create an array object of File type for referencing of cache files
File[] files = getBaseContext().getCacheDir().listFiles();
// use a for etch loop to delete files one by one
for (File file : files) {
/* you can use just [ file.delete() ] function of class File
* or use if for being sure if file deleted
* here if file dose not delete returns false and condition will
* will be true and it ends operation of function by return
* false then we will find that all files are not delete
*/
if (!file.delete()) {
return false; // not success
}
}
// if for loop completes and process not ended it returns true
return true; // success of deleting files
} catch (Exception e) {}
// try stops deleting cache files
return false; // not success
}
getBaseContext (). getCacheDir (). listFiles ()에 의해 File 배열의 모든 캐시 파일을 장비 다음 file.delet () 메서드에 의해 루프에서 하나씩 삭제합니다.
이 시도
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
clearApplicationData();
}
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("EEEEEERRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
}
}
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
int i = 0;
while (i < children.length) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
i++;
}
}
assert dir != null;
return dir.delete();
}
이 코드를 MainActivity의 onStop 메소드에 등록하십시오.
@Override
protected void onStop() {
super.onStop();
AppUtils.deleteCache(getApplicationContext());
}
....
public class AppUtils {
public static void deleteCache(Context context) {
try {
File dir = context.getCacheDir();
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();
} else if(dir!= null && dir.isFile()) {
return dir.delete();
} else {
return false;
}
}
}
참조 URL : https://stackoverflow.com/questions/23908189/clear-cache-in-android-application-programmatically
'ProgramingTip' 카테고리의 다른 글
자바 : 현재 필요한 날짜 형식이 필요한 형식에 맞는지 확인하십시오. (0) | 2021.01.09 |
---|---|
누락 된 값이있는 경우 pandas 데이터 프레임 열을 소문자로 지정하는 방법은 무엇입니까? (0) | 2021.01.09 |
a 전에 모든 것을 얻는 방법 : in a string Python (0) | 2021.01.09 |
mail 명령을 사용하여 이메일을 보낼 때 보낸 사람을 지정합니다. (0) | 2021.01.09 |
한 시트에서 다른 시트로 n 번째 줄마다 복사 (0) | 2021.01.09 |