簡體   English   中英

如何在 API 29 中不推薦使用 getExternalStorageDirectory 時讀取或寫入文件?

[英]How to read or write file as getExternalStorageDirectory is deprecated in API 29?

I am learning android development and i am facing some problem to read getExternalStorageDirectory in java, I have read https://developer.android.com/reference/android/os/Environment but can't understand, can someone help me with example code在 java 中。

文檔中您可以看到:

getExternalStoragePublicDirectory(String type)

此方法在 API 級別 29 中已棄用。為了提高用戶隱私,不推薦直接訪問共享/外部存儲設備。 當應用以 Build.VERSION_CODES.Q 為目標時,應用無法再直接訪問從此方法返回的路徑。 通過遷移到Context#getExternalFilesDir(String)、MediaStore 或 Intent#ACTION_OPEN_DOCUMENT等替代方案,應用程序可以繼續訪問存儲在共享/外部存儲上的內容

不將任何參數作為參數傳遞給此函數,以將您的目錄作為File對象:

context.getExternalFilesDir();

這里的“Context”是一個通過this.getContext();獲取的對象this.getContext();

this是 Activity 的當前對象。 使用時請仔細檢查示波器。

重要的

要訪問內部存儲, AndroidManifest.xml文件中需要Manifest.permission.WRITE_EXTERNAL_STORAGE和/或Manifest.permission.READ_EXTERNAL_STORAGE

可選信息:

  1. 通常,內部存儲在 Android 設備上的路徑為 /sdcard/。 這不是一個真正的路徑,而是一個符號鏈接

  2. 令人困惑的是,Android 中的“外部 sdcard”實際上是指內部設備存儲,而不是外部可彈出的設備外存儲卡存儲。 另請注意,真正的外部SD卡無法完全訪問

  3. Activity類擴展了Context類,這就是我們可以從中獲取上下文的原因。

使用這個靜態方法。 目前我沒有找到任何合法的方法來做到這一點。 所以,我使用這個靜態方法來獲取 root 或 getAbsolutePath 文件路徑。

public static File getAbsoluteDir(Context ctx, String optionalPath) {
        String rootPath;
        if (optionalPath != null && !optionalPath.equals("")) {
            rootPath = ctx.getExternalFilesDir(optionalPath).getAbsolutePath();
        } else {
            rootPath = ctx.getExternalFilesDir(null).getAbsolutePath();
        }
        // extraPortion is extra part of file path
        String extraPortion = "Android/data/" + BuildConfig.APPLICATION_ID
                + File.separator + "files" + File.separator;
        // Remove extraPortion
        rootPath = rootPath.replace(extraPortion, "");
        return new File(rootPath);
    }

使用getExternalFilesDir()getExternalCacheDir()getExternalMediaDirs() (上下文方法)而不是Environment.getExternalStorageDirectory()

String root = mContext.getExternalFilesDir(null).getAbsolutePath();
File myDir = new File(root + "/" + mContext.getResources().getString(R.string.app_name) + "_share");
    myDir.mkdirs();

    
    

簡短答案:

String path = getContext().getExternalFilesDir(null).getAbsolutePath();

2022年,不推薦使用Environment.getExternalStorageDirectoryEnvironment.getExternalStoragePublicDirectory
從 API 29 ~ 31 開始,它們已被標記為已棄用,但不在上面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM