How to use the new SD card access API presented for Android 5.0 (Lollipop)?

后端 未结 3 1223
北荒
北荒 2020-11-22 05:02

Background

On Android 4.4 (KitKat), Google has made access to the SD card quite restricted.

As of Android Lollipop (5.0), developers can use a new API that

3条回答
  •  暖寄归人
    2020-11-22 05:22

    It is just a complementary answer.

    After you created a new file, you might need to save its location into your database and read it tomorrow. You can read retrieve it again using this method:

    /**
     * Get {@link DocumentFile} object from SD card.
     * @param directory SD card ID followed by directory name, for example {@code 6881-2249:Download/Archive},
     *                 where ID for SD card is {@code 6881-2249}
     * @param fileName for example {@code intel_haxm.zip}
     * @return null if does not exist
     */
    public static DocumentFile getExternalFile(Context context, String directory, String fileName){
        Uri uri = Uri.parse("content://com.android.externalstorage.documents/tree/" + directory);
        DocumentFile parent = DocumentFile.fromTreeUri(context, uri);
        return parent != null ? parent.findFile(fileName) : null;
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SettingsFragment.REQUEST_CODE_STORAGE_ACCESS && resultCode == RESULT_OK) {
            int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
            getContentResolver().takePersistableUriPermission(data.getData(), takeFlags);
            String sdcard = data.getDataString().replace("content://com.android.externalstorage.documents/tree/", "");
            try {
                sdcard = URLDecoder.decode(sdcard, "ISO-8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            // for example, sdcardId results "6312-2234"
            String sdcardId = sdcard.substring(0, sdcard.indexOf(':'));
            // save to preferences if you want to use it later
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
            preferences.edit().putString("sdcard", sdcardId).apply();
        }
    }
    

提交回复
热议问题