PublicStorage

Struct PublicStorage 

Source
pub struct PublicStorage<'a, R: Runtime> { /* private fields */ }
Expand description

API of file storage that is available to other applications and users.

§Examples

fn example(app: &tauri::AppHandle) {
    use tauri_plugin_android_fs::AndroidFsExt as _;
 
    let api = app.android_fs();
    let public_storage = api.public_storage();
}

Implementations§

Source§

impl<'a, R: Runtime> SyncPublicStorage<'a, R>

Source

pub fn request_permission(&self) -> Result<bool>

Requests file access permission from the user if needed.

When this function returns true, the app is allowed to create files in PublicStorage and read/write the files it creates. Access to files created by other apps is not guaranteed. Additionally, after the app is uninstalled and reinstalled, previously created files may become inaccessible.

§Version behavior
§Android 11 or higher

Requests no permission.
This function always returns true.

§Android 10

Selects either the behavior for Android 11 or higher or for Android 9 or lower, as needed.

§Android 9 or lower

Requests WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permissions.
To request the permissions, you must declare it in AndroidManifest.xml. By enabling the legacy_storage_permission feature, the permissions will be declared automatically only for Android 9 or lower.

§Support

All Android versions

Source

pub fn has_permission(&self) -> Result<bool>

Indicates whether the app has file access permission.

When this function returns true, the app is allowed to create files in PublicStorage and read/write the files it creates. Access to files created by other apps is not guaranteed. Additionally, after the app is uninstalled and reinstalled, previously created files may become inaccessible.

§Version behavior
§Android 11 or higher

Always returns true.

§Android 10

Selects either the behavior for Android 11 or higher or for Android 9 or lower, as needed.

§Android 9 or lower

Returns true if the app has been granted WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permissions.
See PublicStorage::request_permission for requesting the permissions.

§Support

All Android versions.

Source

pub fn get_volumes(&self) -> Result<Vec<StorageVolume>>

Gets a list of currently available storage volumes (internal storage, SD card, USB drive, etc.). Be aware of TOCTOU.

Since read-only SD cards and similar cases may be included, please use StorageVolume { is_readonly, .. } for filtering as needed.

This typically includes primary storage volume, but it may occasionally be absent if the primary volume is inaccessible (e.g., mounted on a computer, removed, or another issue).

Primary storage volume is always listed first, if included. But the order of the others is not guaranteed.

§Note

For Android 9 (API level 28) or lower, this does not include any storage volumes other than the primary one.

The volume represents the logical view of a storage volume for an individual user: each user may have a different view for the same physical volume. In other words, it provides a separate area for each user in a multi-user environment.

§Support

All Android version.

Source

pub fn get_primary_volume(&self) -> Result<Option<StorageVolume>>

Gets a primary storage volume.
This is the most common and recommended storage volume for placing files that can be accessed by other apps or user. In many cases, it is device’s built-in storage.

A device always has one (and one only) primary storage volume.

Primary volume may not currently be accessible if it has been mounted by the user on their computer, has been removed from the device, or some other problem has happened. If so, this returns None.

§Note

The volume represents the logical view of a storage volume for an individual user: each user may have a different view for the same physical volume. In other words, it provides a separate area for each user in a multi-user environment.

§Support

All Android version.

Source

pub fn create_new_file( &self, volume_id: Option<&StorageVolumeId>, base_dir: impl Into<PublicDir>, relative_path: impl AsRef<Path>, mime_type: Option<&str>, ) -> Result<FileUri>

Creates a new empty file in the specified public directory of the storage volume.
This returns a persistent read-write URI.

The app can read/write it until the app is uninstalled. And it is not removed when the app itself is uninstalled.

§Note
§Android 10 or higher.

Files are automatically registered in the appropriate MediaStore as needed. Scanning is triggered when the file descriptor is closed or as part of the pending lifecycle.

§Android 9 or lower

WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permissions are required.
This needs two steps:

  1. Declare :
    By enabling the legacy_storage_permission feature,
    you can declare the permissions only for Android 9 or lower automatically at build time.

  2. Runtime request :
    By calling PublicStorage::request_permission, you can request the permissions from the user at runtime.

After writing content to the file, call PublicStorage::scan.
Until then, the file may not appear in the gallery or other apps.

§Args
  • volume_id :
    The ID of the storage volume, such as internal storage or an SD card.
    Usually, you don’t need to specify this unless there is a special reason.
    If None is provided, the primary storage volume will be used.

  • base_dir :
    The base directory for the file.
    When using PublicImageDir, only image MIME types should be used for mime_type; using other types may cause errors.
    Similarly, PublicVideoDir and PublicAudioDir should only be used with their respective media types.
    Only PublicGeneralPurposeDir supports all MIME types.

  • relative_path :
    The file path relative to the base directory.
    To keep files organized, it is recommended to place your app’s name directory at the top level.
    Any missing parent directories will be created automatically.
    If a file with the same name already exists, a sequential number is appended to ensure uniqueness.
    If the file has no extension, one may be inferred from mime_type and appended to the file name.
    Strings may also be sanitized as needed, so they may not be used exactly as provided. Note that append-exntesion and sanitize-path operation may vary depending on the device model and Android version.

  • mime_type :
    The MIME type of the file to be created.
    If None, the MIME type will be inferred from the extension of relative_path.
    If that also fails, application/octet-stream will be used.

§Support

All Android version.

Note :

Source

pub fn create_new_file_with_pending( &self, volume_id: Option<&StorageVolumeId>, base_dir: impl Into<PublicDir>, relative_path: impl AsRef<Path>, mime_type: Option<&str>, ) -> Result<FileUri>

Creates a new empty file in the specified public directory of the storage volume.
This returns a persistent read-write URI.

The app can read/write it until the app is uninstalled. And it is not removed when the app itself is uninstalled.

§Note
§Android 10 or higher

Files are automatically registered in the appropriate MediaStore as needed. Scanning is triggered when the file descriptor is closed or as part of the pending lifecycle.

Diffrences from PublicStorage::create_new_file are that files are marked as pending and will not be visible to other apps until PublicStorage::set_pending(..., false) is called.

§Android 9 or lower

This behavior is equal to PublicStorage::create_new_file. So pending is ignored.

WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permissions are required.
This needs two steps:

  1. Declare :
    By enabling the legacy_storage_permission feature,
    you can declare the permissions only for Android 9 or lower automatically at build time.

  2. Runtime request :
    By calling PublicStorage::request_permission, you can request the permissions from the user at runtime.

After writing content to the file, call PublicStorage::scan.
Until then, the file may not appear in the gallery or other apps.

§Args
  • volume_id :
    The ID of the storage volume, such as internal storage or an SD card.
    Usually, you don’t need to specify this unless there is a special reason.
    If None is provided, the primary storage volume will be used.

  • base_dir :
    The base directory for the file.
    When using PublicImageDir, only image MIME types should be used for mime_type; using other types may cause errors.
    Similarly, PublicVideoDir and PublicAudioDir should only be used with their respective media types.
    Only PublicGeneralPurposeDir supports all MIME types.

  • relative_path :
    The file path relative to the base directory.
    To keep files organized, it is recommended to place your app’s name directory at the top level.
    Any missing parent directories will be created automatically.
    If a file with the same name already exists, a sequential number is appended to ensure uniqueness.
    If the file has no extension, one may be inferred from mime_type and appended to the file name.
    Strings may also be sanitized as needed, so they may not be used exactly as provided. Note that append-exntesion and sanitize-path operation may vary depending on the device model and Android version.

  • mime_type :
    The MIME type of the file to be created.
    If None, the MIME type will be inferred from the extension of relative_path.
    If that also fails, application/octet-stream will be used.

§Support

All Android version.

Note :

Source

pub fn create_dir_all( &self, volume_id: Option<&StorageVolumeId>, base_dir: impl Into<PublicDir>, relative_path: impl AsRef<Path>, ) -> Result<()>

Recursively create a directory and all of its parent components if they are missing.
If it already exists, do nothing.

PublicStorage::create_new_file and PublicStorage::create_new_file_with_pending do this automatically, so there is no need to use it together.

§Note

On Android 9 or lower, WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permissions are required.
This needs two steps:

  1. Declare :
    By enabling the legacy_storage_permission feature,
    you can declare the permissions only for Android 9 or lower automatically at build time.

  2. Runtime request :
    By calling PublicStorage::request_permission, you can request the permissions from the user at runtime.

§Args
  • volume_id :
    ID of the storage volume, such as internal storage, SD card, etc.
    If None is provided, the primary storage volume will be used.

  • base_dir :
    The base directory.

  • relative_path :
    The directory path relative to the base directory.
    Strings may also be sanitized as needed, so they may not be used exactly as provided. Note that sanitize-path operation may vary depending on the device model and Android version.

§Support

All Android Version.

Note :

Source

pub fn write_new( &self, volume_id: Option<&StorageVolumeId>, base_dir: impl Into<PublicDir>, relative_path: impl AsRef<Path>, mime_type: Option<&str>, contents: impl AsRef<[u8]>, ) -> Result<FileUri>

Writes contents to the new file in the specified public directory of the storage volume.
This returns a persistent read-write URI.

The app can read/write it until the app is uninstalled. And it is not removed when the app itself is uninstalled.

§Note

On Android 9 or lower, WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permissions are required.
This needs two steps:

  1. Declare :
    By enabling the legacy_storage_permission feature,
    you can declare the permissions only for Android 9 or lower automatically at build time.

  2. Runtime request :
    By calling PublicStorage::request_permission, you can request the permissions from the user at runtime.

§Args
  • volume_id :
    The ID of the storage volume, such as internal storage or an SD card.
    Usually, you don’t need to specify this unless there is a special reason.
    If None is provided, the primary storage volume will be used.

  • base_dir :
    The base directory for the file.
    When using PublicImageDir, only image MIME types should be used for mime_type; using other types may cause errors.
    Similarly, PublicVideoDir and PublicAudioDir should only be used with their respective media types.
    Only PublicGeneralPurposeDir supports all MIME types.

  • relative_path :
    The file path relative to the base directory.
    To keep files organized, it is recommended to place your app’s name directory at the top level.
    Any missing parent directories will be created automatically.
    If a file with the same name already exists, a sequential number is appended to ensure uniqueness.
    If the file has no extension, one may be inferred from mime_type and appended to the file name.
    Strings may also be sanitized as needed, so they may not be used exactly as provided. Note that append-exntesion and sanitize-path operation may vary depending on the device model and Android version.

  • mime_type :
    The MIME type of the file to be created.
    If None, the MIME type will be inferred from the extension of relative_path.
    If that also fails, application/octet-stream will be used.

  • contents :
    Contents.

§Support

All Android version.

Note :

Source

pub fn scan(&self, uri: &FileUri) -> Result<()>

Scans the specified file in MediaStore.
By doing this, the file will be visible with corrent metadata in the Gallery and etc.

You don’t need to call this after PublicStorage::write_new.

§Version behavior
§Android 10 or higher

This function does nothing, because files are automatically registered in the appropriate MediaStore as needed. Scanning is triggered when the file descriptor is closed or as part of the pending lifecycle.

If you really need to perform this operation in this version, please use PublicStorage::_scan.

§Android 9 or lower

Requests the specified file to be scanned by MediaStore.
This function returns when the scan request has been initiated.

§Args
§Support

All Android versions.

Source

pub fn scan_by_path( &self, path: impl AsRef<Path>, mime_type: Option<&str>, ) -> Result<FileUri>

Scans the specified file in MediaStore and returns it’s URI if success.
By doing this, the file will be visible in the Gallery and etc.

§Note

Unlike PublicStorage::scan, this function waits until the scan is complete and then returns either success or an error.

§Args
  • uri :
    Absolute path of the target file. This must be a path obtained from one of the following:

  • mime_type :
    The MIME type of the file.
    If None, the MIME type will be inferred from the extension of the path.
    If that also fails, application/octet-stream will be used.

§Support

All Android version.

Source

pub fn set_pending(&self, uri: &FileUri, is_pending: bool) -> Result<()>

Specifies whether the specified file on PublicStorage is marked as pending.
When set to true, the app has exclusive access to the file, and it becomes invisible to other apps.

If it remains true for more than seven days, the system will automatically delete the file.

§Note

This is available for Android 10 or higher.
On Android 9 or lower, this does nothing.

§Args
§Support

All Android version.

§References
Source

pub fn get_path(&self, uri: &FileUri) -> Result<PathBuf>

👎Deprecated: File operations via paths may result in unstable behaviour and inconsistent outcomes.

Gets the absolute path of the specified file.

§Note

For description and notes on path permissions and handling, see PublicStorage::resolve_path. It involves important constraints and required settings. Therefore, operate files via paths only when it is truly necessary.

§Args
§Support

All Android version.

Source

pub fn resolve_path( &self, volume_id: Option<&StorageVolumeId>, base_dir: impl Into<PublicDir>, ) -> Result<PathBuf>

👎Deprecated: File operations via paths may result in unstable behaviour and inconsistent outcomes.

Retrieves the absolute path for a specified public directory within the given storage volume.
This function does not create any directories; it only constructs the path.

The app is allowed to create files in the directory and read/write the files it creates. Access to files created by other apps is not guaranteed. Additionally, after the app is uninstalled and reinstalled, previously created files may become inaccessible.

The directory is not removed when the app itself is uninstalled.

It is strongly recommended to call PublicStorage::scan_by_path after writing to the file to request registration in MediaStore.

§Note

As shown below, this involves important constraints and required settings. Therefore, operate files via paths only when it is truly necessary.

Do not use operations such as rename or remove that rely on paths (including URIs obtained via FileUri::from_path with this paths), as they may break consistency with the MediaStore on old version. Instead, use the URI obtained through PublicStorage::scan_by_path together with methods such as AndroidFs::rename or AndroidFs::remove_file.

§Android 11 or higher

When using PublicImageDir, use only image type for file name extension, using other type extension or none may cause errors. Similarly, use only the corresponding extesions for PublicVideoDir and PublicAudioDir. Only PublicGeneralPurposeDir supports all extensions and no extension.

§Android 10 or lower

WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permissions are required.
This needs two steps:

  1. Declare :
    By enabling the legacy_storage_permission_include_android_10 feature,
    you can declare the permissions only for Android 10 or lower automatically at build time.

  2. Runtime request :
    By calling PublicStorage::request_permission, you can request the permissions from the user at runtime.

§Android 10

Files within PublicStorage cannot be accessed via file paths, so it is necessary to declare that the app need access PublicStorage using the method of Android 9 or lower.

For it, please set android:requestLegacyExternalStorage="true".

src-tauri/gen/android/app/src/main/AndroidManifest.xml

<manifest ... >
    <application 
        android:requestLegacyExternalStorage="true" 
        ...
    >
        ...
    </application>
</manifest>

And it is not possible to access PublicStorage on volumes other than the primary storage via paths, just like on Android 9 or lower.
But filtering using PublicStorage::get_volumes or StorageVolume::is_available_for_public_storage may not work correctly, as these are intended for access via URIs.

§Args
§Support

All Android version.

Note :

Source

pub fn resolve_initial_location( &self, volume_id: Option<&StorageVolumeId>, base_dir: impl Into<PublicDir>, relative_path: impl AsRef<Path>, create_dir_all: bool, ) -> Result<FileUri>

Builds the specified directory URI.

This should only be used as initial_location in the file picker, such as FilePicker::pick_files. It must not be used for any other purpose.

This is useful when selecting save location, but when selecting existing entries, initial_location is often better with None.

§Args
  • volume_id :
    ID of the storage volume, such as internal storage, SD card, etc.
    If None is provided, the primary storage volume will be used.

  • base_dir :
    The base directory.

  • relative_path :
    The directory path relative to the base directory.

  • create_dir_all :
    Creates directories if missing.
    See PublicStorage::create_dir_all. If error occurs, it will be ignored.

§Support

All Android version.

Note :

Source

pub fn is_audiobooks_dir_available(&self) -> Result<bool>

Verify whether PublicAudioDir::Audiobooks is available on a given device.

If on Android 10 (API level 29) or higher, this returns true.
If on Android 9 (API level 28) and lower, this returns false.

§Support

All Android version.

Source

pub fn is_recordings_dir_available(&self) -> Result<bool>

Verify whether PublicAudioDir::Recordings is available on a given device.

If on Android 12 (API level 31) or higher, this returns true.
If on Android 11 (API level 30) and lower, this returns false.

§Support

All Android version.

Source

pub fn _scan(&self, uri: &FileUri) -> Result<()>

For details, see PublicStorage::scan.

The difference is that this method scans the file even on Android 10 or higher.

On Android 10 or higher, files are automatically registered in the appropriate MediaStore as needed. Scanning is triggered when the file descriptor is closed or as part of the pending lifecycle.
Therefore, please consider carefully whether this is truly necessary.

Source

pub fn _scan_for_result(&self, uri: &FileUri) -> Result<()>

For details, see PublicStorage::_scan.

The difference is that this function waits until the scan is complete and then returns either success or an error.

Auto Trait Implementations§

§

impl<'a, R> Freeze for SyncPublicStorage<'a, R>

§

impl<'a, R> RefUnwindSafe for SyncPublicStorage<'a, R>

§

impl<'a, R> Send for SyncPublicStorage<'a, R>

§

impl<'a, R> Sync for SyncPublicStorage<'a, R>

§

impl<'a, R> Unpin for SyncPublicStorage<'a, R>

§

impl<'a, R> UnwindSafe for SyncPublicStorage<'a, R>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> ErasedDestructor for T
where T: 'static,