Development Tip

Android에서 캐시 디렉토리를 언제 지울까요?

yourdevel 2020. 10. 15. 21:51
반응형

Android에서 캐시 디렉토리를 언제 지울까요?


인터넷에서 사진을 표시하는 애플리케이션이 있습니다 (디자이너 작업을위한 쇼케이스). 내부 캐시 디렉터리에서 콘텐츠 캐싱을 시작하지만 앱 콘텐츠의 캐시 크기는 약 150MB가 소요될 수 있습니다. 그리고 안드로이드 문서가 말하는 것 :

항상 캐시 파일을 직접 유지하고 1MB와 같이 사용 된 공간의 합당한 한계 내에서 유지해야합니다. 사용자가 애플리케이션을 제거하면 이러한 파일이 제거됩니다.

그래서 Currents 앱 (Galaxy Nexus)을 살펴 봤는데 애플리케이션의 캐시 크기는 110MB입니다. 하지만 이상한 점은 Google 세상보기 및 Google지도와 같은 애플리케이션이 (USB 저장소 데이터)라는 콘텐츠를 캐시한다는 것입니다.

여기에 이미지 설명 입력

그래서 이전 응용 프로그램에서 사용하는 'USB 저장 데이터'는 무엇입니까? 그리고 응용 프로그램에서 캐싱을 구현하는 경우 캐시의 모든 응용 프로그램 파일 을 반복 하여 무언가를 삽입 한 다음 비교하고 지워야 할 때마다 크기를 얻습니까? 아니면 Android가 일부 애플리케이션 캐시 디렉토리를 정리할 시간을 결정할 때까지 콘텐츠를 계속 캐싱합니까?

저는 Android에서 캐시를 관리하는 흐름이 무엇인지 또는 적어도 다른 애플리케이션이 캐시 할 대용량 콘텐츠로 무엇을하는지 알고 싶습니다.


질문을하기 전에 두 가지 스토리지 유형에 대한 간략한 설명이 있습니다.

은닉처

이것은 파일 시스템의 앱별 디렉토리입니다. 이 디렉토리의 목적은 애플리케이션이 세션간에 보관해야하는 임시 데이터를 저장하는 것입니다.하지만 이러한 데이터를 영원히 보관하는 것이 중요하지 않을 수도 있습니다. 일반적으로 Context.getCacheDir(). 앱 설정에 '캐시'로 표시됩니다.

파일

캐시 디렉터리와 마찬가지로 앱에도 파일을 보관하기위한 앱별 디렉터리가 있습니다. 이 디렉토리의 파일은 앱이 명시 적으로 삭제하거나 앱이 제거 될 때까지 존재합니다. 일반적으로 Context.getFilesDir(). 이것은 앱 정보 화면에 여러 가지로 표시 될 수 있지만 스크린 샷에서는 "USB 저장소 데이터"입니다.

참고 : 외부 미디어 (일반적으로 SD 카드)에 명시 적으로 배치하려는 경우 Context.getExternalFilesDir(String type).

차이점

두 디렉토리 모두 애플리케이션에만 해당됩니다 (다른 앱은 액세스 권한이 없음). 캐시와 파일 디렉토리의 차이점 중 하나는 시스템의 저장 공간이 부족할 경우 리소스를 확보 할 첫 번째 장소가 캐시 디렉토리라는 것입니다. 시스템은 파일 디렉토리에서 데이터를 지우지 않습니다. 또 다른 차이점은 캐시 디렉터리는 일반적으로 앱 정보 화면에서 수동으로 지울 수 있다는 것입니다. 일반적으로 파일 디렉터리도 가능하지만 파일 디렉터리를 지우면 캐시 디렉터리도 지워집니다.

어느 것을 사용합니까?

앱의 수명과 비교하여 데이터가 얼마나 중요한지에 따라 다릅니다. 한 세션에 대한 데이터 만 필요하고 해당 데이터를 다시 사용해야할지 의심 스러우면 둘 중 하나를 사용하지 마십시오. 필요하지 않을 때까지 메모리에 보관하십시오. 여러 세션간에 데이터를 재사용해야한다고 생각되지만 하드 카피를 보관할 필요가없는 경우 캐시 디렉토리를 사용하십시오. 이 데이터가 무엇이든 상관없이 필요하거나 영구 저장소가 필요한 대용량 데이터 인 경우 files 디렉토리를 사용하십시오. 내가 생각할 수있는 몇 가지 예는 다음과 같습니다.

  • 캐시-최근에 연 이메일
    • 일단 열리면 데이터를 캐시하여 사용자가 해당 이메일을 다시 읽고 싶을 때 동일한 데이터를 검색하기 위해 네트워크를 다시 사용하는 대신 즉시로드합니다. 결국 사용자가 이메일로 끝날 것이기 때문에 이것을 영원히 유지할 필요가 없습니다.
  • 파일-이메일에서 다운로드 한 첨부 파일
    • 이것은 "이 데이터를 보관하여 필요할 때마다 백업 할 수 있도록하고 싶습니다."라고 말하는 사용자의 작업입니다. 따라서 사용자가 삭제하기를 원할 때까지이 파일을 삭제하고 싶지 않으므로 파일 디렉터리에 넣으십시오.

언제 캐시 디렉토리를 지워야합니까?

로부터 Context.getCacheDir()의 javadoc :

참고 : 이러한 파일을 삭제하는 시스템에 의존해서는 안됩니다. 캐시 파일로 사용하는 공간의 양에 대해 항상 적절한 최대 값 (예 : 1MB)이 있어야하며 해당 공간을 초과하면 해당 파일을 정리해야합니다.

1MB의 예를 사용하지만 앱에 합리적 일 수도 있고 그렇지 않을 수도 있습니다. 그럼에도 불구하고 하드 최대 값을 설정해야합니다. 그 이유는 단순히 책임감있는 앱을 디자인하기 때문입니다. 그럼 언제 확인해야합니까? 캐시 디렉토리에 무언가를 넣고 싶을 때마다 확인하는 것이 좋습니다. 다음은 매우 간단한 캐시 관리자입니다.

public class CacheManager {

    private static final long MAX_SIZE = 5242880L; // 5MB

    private CacheManager() {

    }

    public static void cacheData(Context context, byte[] data, String name) throws IOException {

        File cacheDir = context.getCacheDir();
        long size = getDirSize(cacheDir);
        long newSize = data.length + size;

        if (newSize > MAX_SIZE) {
            cleanDir(cacheDir, newSize - MAX_SIZE);
        }

        File file = new File(cacheDir, name);
        FileOutputStream os = new FileOutputStream(file);
        try {
            os.write(data);
        }
        finally {
            os.flush();
            os.close();
        }
    }

    public static byte[] retrieveData(Context context, String name) throws IOException {

        File cacheDir = context.getCacheDir();
        File file = new File(cacheDir, name);

        if (!file.exists()) {
            // Data doesn't exist
            return null;
        }

        byte[] data = new byte[(int) file.length()];
        FileInputStream is = new FileInputStream(file);
        try {
            is.read(data);
        }
        finally {
            is.close();
        }

        return data;
    }

    private static void cleanDir(File dir, long bytes) {

        long bytesDeleted = 0;
        File[] files = dir.listFiles();

        for (File file : files) {
            bytesDeleted += file.length();
            file.delete();

            if (bytesDeleted >= bytes) {
                break;
            }
        }
    }

    private static long getDirSize(File dir) {

        long size = 0;
        File[] files = dir.listFiles();

        for (File file : files) {
            if (file.isFile()) {
                size += file.length();
            }
        }

        return size;
    }
}

물론 이것은 비용이 많이 드는 작업 일 수 있으므로 백그라운드 스레드에서 캐싱을 계획해야합니다.

또한 이것은 필요한만큼 복잡 할 수 있습니다. 내 예에서는 캐시 된 모든 파일이 캐시 디렉터리의 루트에 있다고 가정하므로 잠재적 인 하위 디렉터리를 확인하지 않습니다. 가장 오래된 액세스 날짜로 파일을 삭제하는 것과 같이 파일을 삭제하는 루틴도 더 복잡해질 수 있습니다.

One thing to keep in mind when deciding to cache data is that you need to always plan for the case that your cached data no longer exists. Always have a routine in place to retrieve data by external means when your cache doesn't have it in storage. Likewise, always check your cache before retrieve data externally. The purpose of the cache is to cut down on network activity, long processes, and provide a responsive UI in your app. So use it responsibly :)


i thing best way to clearing app cache when activity finish so that every time cache clear when new activity call.

put this code in onDestroy() for clear app cache

@Override
protected void onDestroy() {

    super.onDestroy();
    try {
        trimCache(this);
       // Toast.makeText(this,"onDestroy " ,Toast.LENGTH_LONG).show();
    } 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();
}

I think the idea behind the cache is to write anything you want on it and Android will manage its size if it gets too high.

You should keep in mind that you can write files to the cache, but always checks if the file is still saved when trying to access it. And let android manage th cache.


Depends on the type of application:

  • Some applications only use single sessions and don't need to remember any data, so you can clear the cache when you want (some apps even do this automatically in their onStop activity)
  • Most application keep your data because they remember your settings, the account you have used to log in,... In this case, it's best to only clear the cache when you don't use the application a lot.

Also:

So i took a look at Chrome app (Galaxy Nexus) and the cache size for the application is 110 MB. But what wired is that applications like Google current & Google maps cache the content in something called (USB Storage Data) :

AFAIK, Usb storage data has a different use from cache: the storage is to store program specific information (like maps for a GPS app), the cache is used to store user specific information (like logins)

Google지도의 경우 :지도 데이터를 USB 저장소에 저장하고 캐시에 설정 및 검색 기록을 유지한다고 가정합니다. ==>지도 데이터는 애플리케이션에 따라 다르며 설정 및 검색 기록은 사용자에 따라 다릅니다.


문서에 따르면 시스템은 장치의 내부 저장 공간이 부족할 때 캐시를 지 웁니다 . API8 이후로 내가 읽은 이후 유용한 getExternalCacheDir () 메서드가 있습니다.

참고 URL : https://stackoverflow.com/questions/9942560/when-to-clear-the-cache-dir-in-android

반응형