Context#getExternalFilesDir, 안드로이드의 다양한 저장소 디렉토리 사용 요약

Context 클래스는 휴대폰 시스템의 디렉터리를 얻기 위한 몇 가지 API를 정의합니다. 요약은 다음과 같습니다.

1. API 댓글 번역

1、파일 getExternalFilesDir(@Nullable 문자열 유형)

@Nullable
public abstract File getExternalFilesDir(@Nullable String type);
    /**
     * Returns the absolute path to the directory on the primary shared/external
     * storage device where the application can place persistent files it owns.
     * These files are internal to the applications, and not typically visible
     * to the user as media.
     * <p>
     * This is like {@link #getFilesDir()} in that these files will be deleted
     * when the application is uninstalled, however there are some important
     * differences:
     * <ul>
     * <li>Shared storage may not always be available, since removable media can
     * be ejected by the user. Media state can be checked using
     * {@link Environment#getExternalStorageState(File)}.
     * <li>There is no security enforced with these files. For example, any
     * application holding
     * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
     * these files.
     * </ul>
     * <p>
     * If a shared storage device is emulated (as determined by
     * {@link Environment#isExternalStorageEmulated(File)}), it's contents are
     * backed by a private user data partition, which means there is little
     * benefit to storing data here instead of the private directories returned
     * by {@link #getFilesDir()}, etc.
     * <p>
     * Starting in {@link android.os.Build.VERSION_CODES#KITKAT}, no permissions
     * are required to read or write to the returned path; it's always
     * accessible to the calling app. This only applies to paths generated for
     * package name of the calling application. To access paths belonging to
     * other packages,
     * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} and/or
     * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} are required.
     * <p>
     * On devices with multiple users (as described by {@link UserManager}),
     * each user has their own isolated shared storage. Applications only have
     * access to the shared storage for the user they're running as.
     * <p>
     * The returned path may change over time if different shared storage media
     * is inserted, so only relative paths should be persisted.
     * <p>
     * Here is an example of typical code to manipulate a file in an
     * application's shared storage:
     * </p>
     * {@sample development/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java
     * private_file}
     * <p>
     * If you supply a non-null <var>type</var> to this function, the returned
     * file will be a path to a sub-directory of the given type. Though these
     * files are not automatically scanned by the media scanner, you can
     * explicitly add them to the media database with
     * {@link android.media.MediaScannerConnection#scanFile(Context, String[], String[], android.media.MediaScannerConnection.OnScanCompletedListener)
     * MediaScannerConnection.scanFile}. Note that this is not the same as
     * {@link android.os.Environment#getExternalStoragePublicDirectory
     * Environment.getExternalStoragePublicDirectory()}, which provides
     * directories of media shared by all applications. The directories returned
     * here are owned by the application, and their contents will be removed
     * when the application is uninstalled. Unlike
     * {@link android.os.Environment#getExternalStoragePublicDirectory
     * Environment.getExternalStoragePublicDirectory()}, the directory returned
     * here will be automatically created for you.
     * <p>
     * Here is an example of typical code to manipulate a picture in an
     * application's shared storage and add it to the media database:
     * </p>
     * {@sample development/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java
     * private_picture}
     *
     * @param type The type of files directory to return. May be {@code null}
     *            for the root of the files directory or one of the following
     *            constants for a subdirectory:
     *            {@link android.os.Environment#DIRECTORY_MUSIC},
     *            {@link android.os.Environment#DIRECTORY_PODCASTS},
     *            {@link android.os.Environment#DIRECTORY_RINGTONES},
     *            {@link android.os.Environment#DIRECTORY_ALARMS},
     *            {@link android.os.Environment#DIRECTORY_NOTIFICATIONS},
     *            {@link android.os.Environment#DIRECTORY_PICTURES}, or
     *            {@link android.os.Environment#DIRECTORY_MOVIES}.
     * @return the absolute path to application-specific directory. May return
     *         {@code null} if shared storage is not currently available.
     * @see #getFilesDir
     * @see #getExternalFilesDirs(String)
     * @see Environment#getExternalStorageState(File)
     * @see Environment#isExternalStorageEmulated(File)
     * @see Environment#isExternalStorageRemovable(File)
     */

        함수 api 설명 정보의 번역은 다음과 같습니다.

        getExternalFilesDir 함수는 애플리케이션이 자체 영구 파일을 저장할 수 있는 기본 공유/외부 저장 장치 디렉토리의 절대 경로를 반환합니다. 이러한 영구 파일은 프로그램 내부에 있으며 일반적으로 사용자에게 미디어로 표시되지 않습니다.

        응용 프로그램이 제거되면 이러한 파일도 삭제되며 이는 getFilesDir() 함수와 다소 유사합니다. 그러나 이들 사이에는 다음과 같은 몇 가지 중요한 차이점이 있습니다.

  • 사용자가 이동식 미디어 장치를 꺼낼 수 있기 때문에 공유 저장소를 항상 사용할 수 있는 것은 아닙니다. Environment#getExternalStorageState(File)를 사용하여 미디어 상태를 확인할 수 있습니다.
  • 이러한 파일에 대한 보안 시행은 없습니다. 예를 들어 android.Manifest.permission#WRITE_EXTERNAL_STORAGE 권한이 있는 애플리케이션은 이러한 파일을 변경할 수 있습니다.

        공유 저장 장치가 에뮬레이트된 경우(Environment#isExternalStorageEmulated(File)에 의해 결정됨) 해당 콘텐츠는 개인 사용자 데이터 파티션에 의해 지원됩니다. 즉, getFilesDir()을 사용하는 대신 여기에 데이터를 저장하는 것이 약간의 이점이 있습니다. 예배 규칙서.

        android.os.Build.VERSION_CODES#KITKAT(sdk19, 즉 android 4.4)부터는 이러한 반환된 디렉토리를 읽고 쓰는 데 더 이상 권한이 필요하지 않습니다. 이러한 디렉터리는 현재 이 함수를 호출하는 앱에서 항상 액세스할 수 있습니다. 이는 호출 애플리케이션의 패키지 이름에 대해 생성된 경로에만 적용됩니다. 다른 패키지 이름에 속한 경로에 접근하려면 android.Manifest.permission#WRITE_EXTERNAL_STORAGE 및 READ_EXTERNAL_STORAGE 권한을 얻어야 합니다.

        다중 사용자 장치에서 각 사용자는 자신만의 독립적인 공유 저장소 디렉터리를 가집니다. 애플리케이션은 현재 실행 중인 사용자의 공유 디렉토리에만 액세스할 수 있습니다.

        반환된 경로는 다른 공유 저장 매체가 연결된 경우 시간이 지남에 따라 변경될 수 있으므로 상대 경로만 보존해야 합니다.

        다음은 애플리케이션 공유 저장소에서 파일을 조작하기 위한 일반 코드의 예제 private_file입니다. http://androidxref.com/9.0.0_r3/xref/development/samples/ApiDemos/src/com/example/android/apis/ content 링크를 참조하세요. /ExternalStorage.java

        이 함수에 null이 아닌 인수를 전달하면 반환된 경로는 지정된 디렉터리의 하위 디렉터리가 됩니다. 미디어 스캐너는 이러한 파일을 자동으로 검색하지 않지만 MediaScannerConnection.scanFile을 사용하여 미디어 데이터베이스에 명시적으로 추가할 수 있습니다.

        이것은 모든 애플리케이션이 공유하는 미디어 디렉토리를 제공하는 Environment.getExternalStoragePublicDirectory()와 다릅니다. 여기에 반환된 디렉터리는 응용 프로그램 자체만 소유하며 응용 프로그램이 제거되면 삭제됩니다. Environment.getExternalStoragePublicDirectory()와 달리 여기에 반환된 디렉터리는 자동으로 생성됩니다.

        다음은 응용 프로그램의 공유 저장소에서 사진을 조작하고 미디어 데이터베이스에 사진을 추가하기 위한 일반 코드의 private_picture 예제입니다. http://androidxref.com/9.0.0_r3/xref/development/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java 링크 참조

        유형 매개변수 설명:

        type은 반환할 파일 디렉토리의 유형을 나타내며 null 또는 다른 값일 수 있습니다. null은 파일 디렉토리의 루트 디렉토리를 나타내고 다른 값은 각각 루트 디렉토리의 하위 디렉토리를 나타냅니다.

환경#DIRECTORY_MUSIC

환경#DIRECTORY_PODCASTS

환경#DIRECTORY_RINGTONES

환경#DIRECTORY_ALARMS

환경#DIRECTORY_NOTIFICATIONS

환경#DIRECTORY_PICTURES

환경#DIRECTORY_MOVIES        

        반환 값 설명: 응용 프로그램에서 지정한 디렉터리의 절대 경로 현재 공유 저장소를 사용할 수 없는 경우 null이 반환될 수 있습니다.

참고:

Context#getFilesDir
Context#getExternalFilesDirs(String)
환경#getExternalStorageState(파일)
환경#isExternalStorageEmulated(파일)
환경#isExternalStorageRemovable(파일)

2. 참고 기사

거의 끝났고 아직 함수가 반환하는 특정 경로를 소개하지 않았습니다. 여기에 추가하겠습니다.

  1. 이 메서드 는 /storage/emulated/0/Android/data/packageName/files 에서 외부 저장소를 가져오는 데 사용됩니다.
  2. 이 메소드는 경로 아래에 폴더로 표현되는 문자열 유형 매개변수를 전달할 수 있으며, 해당 폴더가 없으면 자동으로 생성됩니다.
  3. 지침
    ​String path=context.getExternalFilesDir(null).getAbsolutePath();
    File file=new File(path);
    //输出:path:/storage/emulated/0/Android/data/backageName/files
    
    String path2=context.getExternalFilesDir("UniApp").getAbsolutePath();
    File file2=new File(path2);
    //path:/storage/emulated/0/Android/data/packageName/files/UniApp
    //如uniapp文件夹没有,则会自动创建
    
    String path3=context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
    File file3=new File(path3);
    //path:/storage/emulated/0/Android/data/packageName/files/Download
    
    
    String path4=context.getExternalFilesDir("").getAbsolutePath()+"/hhhhhh";
    File file4=new File(path4);
    //path:storage/emulated/0/Android/data/packageName/files/hhhhhh
    //如果没有“hhhhhh”文件夹,则file4.exists()==false;
    

    4. 이 디렉토리는 주로 응용 프로그램의 일부 개인 파일을 저장하는 데 사용됩니다 . 이 디렉터리에는 여러 속성이 있습니다.

자동 삭제
        이 파일은 앱 제거 시 삭제됩니다. 물론 sd카드가 있다는 전제하에요.

이러한 파일 에 액세스하는 다른 애플리케이션은
        다른 애플리케이션에서 액세스할 수 있지만 전제는 다른 애플리케이션에 외부 저장소 권한이 있다는 것입니다.

        하지만 Android 11 이후에도 다른 앱은 저장 권한이 있더라도 이러한 파일에 액세스할 수 없습니다.

저장소 권한
         Android api 19(예: 4.4) 이후에는 이 앱이 SD 카드에 있지만 저장소 권한 없이도 이러한 파일에 액세스할 수 있습니다. 공식 문서는 다음과 같습니다.

{@link android.os.Build.VERSION_CODES#KITKAT}부터는
반환된 경로를 읽거나 쓰는 데 권한이 필요하지 않습니다.
호출 앱에서 항상 액세스할 수 있습니다 .
이는 호출 애플리케이션의 패키지 이름 에 대해 생성된 경로에만 적용됩니다 .
다른 패키지 에 속한 경로에 액세스하려면

        대부분의 앱의 minSdkVersion이 19 이상이므로 이 디렉터리를 사용할 때 저장소 권한을 요청할 필요가 없습니다.

3. getExternalFilesDirs와의 차이점

        getExternalFilesDirs의 주석을 살펴보겠습니다.

* @return the absolute paths to application-specific directories. Some
*         individual paths may be {@code null} if that shared storage is
*         not currently available. The first path returned is the same as
*         {@link #getExternalFilesDir(String)}.

        getExternalFilesDirs 함수가 반환하는 것은 애플리케이션에서 지정한 디렉터리 컬렉션의 절대 경로입니다. 공유 저장소를 현재 사용할 수 없는 경우 일부 독립 경로 컬렉션은 null일 수 있습니다. 반환된 첫 번째 경로는 getExternalFilesDir(String)과 동일합니다.

        다음으로 중단점을 통해 디버그하여 getExternalFilesDirs의 반환 경로 배열의 특정 값에 포함된 내용을 확인합니다.

 참조 문서:

1. getExternalFilesDir_BennuCTech의 블로그-CSDN Blog_getexternalfilesdir이 정확히 무엇입니까?

2. [Android] getExternalFilesDir()의 내부 매개변수

3. Android 호환성 시리즈 기사 5: 메모리 카드 - 너겟

Supongo que te gusta

Origin blog.csdn.net/liuqinhou/article/details/127177192
Recomendado
Clasificación