Trait AndroidFs

Source
pub trait AndroidFs<R: Runtime> {
Show 34 methods // Required methods fn get_name(&self, uri: &FileUri) -> Result<String>; fn get_mime_type(&self, uri: &FileUri) -> Result<Option<String>>; fn open_file(&self, uri: &FileUri, mode: FileAccessMode) -> Result<File>; fn copy_via_kotlin(&self, src: &FileUri, dest: &FileUri) -> Result<()>; fn remove_file(&self, uri: &FileUri) -> Result<()>; fn remove_dir(&self, uri: &FileUri) -> Result<()>; fn create_file( &self, dir: &FileUri, relative_path: impl AsRef<str>, mime_type: Option<&str>, ) -> Result<FileUri>; fn read_dir(&self, uri: &FileUri) -> Result<impl Iterator<Item = Entry>>; fn show_open_file_dialog( &self, initial_location: Option<&FileUri>, mime_types: &[&str], multiple: bool, ) -> Result<Vec<FileUri>>; fn show_open_visual_media_dialog( &self, target: VisualMediaTarget, multiple: bool, ) -> Result<Vec<FileUri>>; fn show_manage_dir_dialog( &self, initial_location: Option<&FileUri>, ) -> Result<Option<FileUri>>; fn show_save_file_dialog( &self, initial_location: Option<&FileUri>, initial_file_name: impl AsRef<str>, mime_type: Option<&str>, ) -> Result<Option<FileUri>>; fn show_share_file_dialog(&self, uri: &FileUri) -> Result<()>; fn show_view_file_dialog(&self, uri: &FileUri) -> Result<()>; fn can_share_file(&self, uri: &FileUri) -> Result<bool>; fn can_view_file(&self, uri: &FileUri) -> Result<bool>; fn take_persistable_uri_permission(&self, uri: &FileUri) -> Result<()>; fn check_persisted_uri_permission( &self, uri: &FileUri, mode: PersistableAccessMode, ) -> Result<bool>; fn get_all_persisted_uri_permissions( &self, ) -> Result<impl Iterator<Item = PersistedUriPermission>>; fn release_persisted_uri_permission(&self, uri: &FileUri) -> Result<()>; fn release_all_persisted_uri_permissions(&self) -> Result<()>; fn is_visual_media_dialog_available(&self) -> Result<bool>; fn private_storage(&self) -> &impl PrivateStorage<R>; fn public_storage(&self) -> &impl PublicStorage<R>; fn app_handle(&self) -> &AppHandle<R>; // Provided methods fn is_available(&self) -> bool { ... } fn get_metadata(&self, uri: &FileUri) -> Result<Metadata> { ... } fn read(&self, uri: &FileUri) -> Result<Vec<u8>> { ... } fn read_to_string(&self, uri: &FileUri) -> Result<String> { ... } fn write(&self, uri: &FileUri, contents: impl AsRef<[u8]>) -> Result<()> { ... } fn write_via_kotlin( &self, uri: &FileUri, contents: impl AsRef<[u8]>, ) -> Result<()> { ... } fn write_via_kotlin_in<T>( &self, uri: &FileUri, contents_writer: impl FnOnce(&mut File) -> Result<T>, ) -> Result<T> { ... } fn need_write_via_kotlin(&self, uri: &FileUri) -> Result<bool> { ... } fn show_open_dir_dialog(&self) -> Result<Option<FileUri>> { ... }
}
Expand description

API

Required Methods§

Source

fn get_name(&self, uri: &FileUri) -> Result<String>

Get the file or directory name.

§Args
  • uri :
    Target URI.
    This needs to be readable.
§Support

All Android version.

Source

fn get_mime_type(&self, uri: &FileUri) -> Result<Option<String>>

Query the provider to get mime type.
If the directory, this returns None.
If the file, this returns no None.
If the file type is unknown or unset, this returns Some("application/octet-stream").

§Args
  • uri :
    Target URI.
    This needs to be readable.
§Support

All Android version.

Source

fn open_file(&self, uri: &FileUri, mode: FileAccessMode) -> Result<File>

Open a file in the specified mode.

§Args
  • uri :
    Target file URI.
    This must have corresponding permissions (read, write, or both) for the specified mode.

  • mode :
    Indicates how the file is opened and the permissions granted.
    Note that files provided by third-party apps may not support FileAccessMode::WriteAppend. (ex: Files on GoogleDrive)

§Note

This method uses a FileDescriptor internally. However, if the target file does not physically exist on the device, such as cloud-based files, the write operation using a FileDescriptor may not be reflected properly. In such cases, consider using AndroidFs::write_via_kotlin, which writes using a standard method, or AndroidFs::write, which automatically falls back to that approach when necessary. If you specifically need to write using std::fs::File not entire contents, see AndroidFs::write_via_kotlin_in or AndroidFs::copy_via_kotlin.

It seems that the issue does not occur on all cloud storage platforms. At least, files on Google Drive have issues, but files on Dropbox can be written to correctly using a FileDescriptor. If you encounter issues with cloud storage other than Google Drive, please let me know on Github. This information will be used in AndroidFs::need_write_via_kotlin used by AndroidFs::write.

There are no problems with file reading.

§Support

All Android version.

Source

fn copy_via_kotlin(&self, src: &FileUri, dest: &FileUri) -> Result<()>

Copies the contents of src file to dest.

This copy process is done on Kotlin side, not on Rust.
Large files in GB units are also supported.

See AndroidFs::write_via_kotlin for why this function exists.

§Args
  • src :
    The URI of source file.
    This needs to be readable.

  • dest :
    The URI of destination file.
    This needs to be writable.

§Support

All Android version.

Source

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

Remove the file.

§Args
  • uri :
    Target file URI.
    This needs to be writable, at least. But even if it is, removing may not be possible in some cases. For details, refer to the documentation of the function that provided the URI.
§Support

All Android version.

Source

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

Remove the empty directory.

§Args
  • uri :
    Target directory URI.
    This needs to be writable.
§Support

All Android version.

Source

fn create_file( &self, dir: &FileUri, relative_path: impl AsRef<str>, mime_type: Option<&str>, ) -> Result<FileUri>

Creates a new empty file in the specified location and returns a URI.

The permissions and validity period of the returned URIs depend on the origin directory (e.g., the top directory selected by AndroidFs::show_open_dir_dialog)

§Args
  • dir :
    The URI of the base directory.
    This needs to be read-write.

  • relative_path :
    The file path relative to the base directory.
    If a file with the same name already exists, a sequential number will be appended to ensure uniqueness.
    Any missing subdirectories in the specified path will be created automatically.

  • mime_type :
    The MIME type of the file to be created.
    If this is None, MIME type is inferred from the extension and if that fails, application/octet-stream is used.

§Support

All Android version.

Source

fn read_dir(&self, uri: &FileUri) -> Result<impl Iterator<Item = Entry>>

Returns the child files and directories of the specified directory.
The order of the entries is not guaranteed.

The permissions and validity period of the returned URIs depend on the origin directory (e.g., the top directory selected by AndroidFs::show_open_dir_dialog)

§Args
  • uri :
    Target directory URI.
    This needs to be readable.
§Note

The returned type is an iterator because of the data formatting and the file system call is not executed lazily. Thus, for directories with thousands or tens of thousands of elements, it may take several seconds.

§Support

All Android version.

Source

fn show_open_file_dialog( &self, initial_location: Option<&FileUri>, mime_types: &[&str], multiple: bool, ) -> Result<Vec<FileUri>>

Opens a system file picker and returns a read-write URIs.
If no file is selected or the user cancels, an empty vec is returned.

This provides a relatively consistent interface regardless of version or device, and also allows file selection from third-party apps or cloud storage.

By default, returned URI is valid until the app is terminated. If you want to persist it across app restarts, use AndroidFs::take_persistable_uri_permission.

Removing the returned files is also supported in most cases, but note that files provided by third-party apps may not be removable.

Just to read images and videos, consider using AndroidFs::show_open_visual_media_dialog instead.

§Args
  • initial_location :
    Indicate the initial location of dialog.
    System will do its best to launch the dialog in the specified entry if it’s a directory, or the directory that contains the specified file if not.
    If this is missing or failed to resolve the desired initial location, the initial location is system specific.

  • mime_types :
    The MIME types of the file to be selected.
    However, there is no guarantee that the returned file will match the specified types.
    If left empty, all file types will be available (equivalent to ["*/*"]).

  • multiple :
    Indicates whether multiple file selection is allowed.

§Issue

This dialog has known issues. See the following for details and workarounds

§Support

All Android version.

§References

https://developer.android.com/reference/android/content/Intent#ACTION_OPEN_DOCUMENT

Source

fn show_open_visual_media_dialog( &self, target: VisualMediaTarget, multiple: bool, ) -> Result<Vec<FileUri>>

Opens a media picker and returns a readonly URIs.
If no file is selected or the user cancels, an empty vec is returned.

This media picker provides a browsable interface that presents the user with their media library, sorted by date from newest to oldest.

By default, returned URI is valid until the app is terminated. If you want to persist it across app restarts, use AndroidFs::take_persistable_uri_permission.

§Args
  • target :
    The media type of the file to be selected.
    Images or videos, or both.

  • multiple :
    Indicates whether multiple file selection is allowed.

§Issue

This dialog has known issues. See the following for details and workarounds

§Note

The file obtained from this function cannot retrieve the correct file name using AndroidFs::get_name.
Instead, it will be assigned a sequential number, such as 1000091523.png. And this is marked intended behavior, not a bug.

§Support

This feature is available on devices that meet the following criteria:

  • Running Android 11 (API level 30) or higher
  • Receive changes to Modular System Components through Google System Updates

Availability on a given device can be verified by calling AndroidFs::is_visual_media_dialog_available.
If not supported, this function behaves the same as AndroidFs::show_open_file_dialog.

§References

https://developer.android.com/training/data-storage/shared/photopicker

Source

fn show_manage_dir_dialog( &self, initial_location: Option<&FileUri>, ) -> Result<Option<FileUri>>

Opens a system directory picker, allowing the creation of a new directory or the selection of an existing one, and returns a read-write directory URI. App can fully manage entries within the returned directory.
If no directory is selected or the user cancels, None is returned.

By default, returned URI is valid until the app is terminated. If you want to persist it across app restarts, use AndroidFs::take_persistable_uri_permission.

§Args
  • initial_location :
    Indicate the initial location of dialog.
    System will do its best to launch the dialog in the specified entry if it’s a directory, or the directory that contains the specified file if not.
    If this is missing or failed to resolve the desired initial location, the initial location is system specific.
§Issue

This dialog has known issues. See the following for details and workarounds

§Support

All Android version.

§References

https://developer.android.com/reference/android/content/Intent#ACTION_OPEN_DOCUMENT_TREE

Source

fn show_save_file_dialog( &self, initial_location: Option<&FileUri>, initial_file_name: impl AsRef<str>, mime_type: Option<&str>, ) -> Result<Option<FileUri>>

Opens a dialog to save a file and returns a writeonly URI.
The returned file may be a newly created file with no content, or it may be an existing file with the requested MIME type.
If the user cancels, None is returned.

By default, returned URI is valid until the app is terminated. If you want to persist it across app restarts, use AndroidFs::take_persistable_uri_permission.

Removing and reading the returned files is also supported in most cases, but note that files provided by third-party apps may not.

§Args
  • initial_location :
    Indicate the initial location of dialog.
    System will do its best to launch the dialog in the specified entry if it’s a directory, or the directory that contains the specified file if not.
    If this is missing or failed to resolve the desired initial location, the initial location is system specific.

  • initial_file_name :
    An initial file name, but the user may change this value before creating the file.

  • mime_type :
    The MIME type of the file to be saved.
    If this is None, MIME type is inferred from the extension and if that fails, application/octet-stream is used.

§Issue

This dialog has known issues. See the following for details and workarounds

§Support

All Android version.

§References

https://developer.android.com/reference/android/content/Intent#ACTION_CREATE_DOCUMENT

Source

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

Opens a dialog for sharing file to other apps.

An error will occur if there is no app that can handle the request. Please use AndroidFs::can_share_file to confirm.

§Args
§Support

All Android version.

Source

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

Opens a dialog for viewing file on other apps.
This performs the general “open file” action.

An error will occur if there is no app that can handle the request. Please use AndroidFs::can_view_file to confirm.

§Args
§Support

All Android version.

Source

fn can_share_file(&self, uri: &FileUri) -> Result<bool>

Determines whether the specified file can be used with AndroidFs::show_share_file_dialog.

§Args
  • uri :
    Target file uri.
    This needs to be readable.
§Support

All Android version.

Source

fn can_view_file(&self, uri: &FileUri) -> Result<bool>

Determines whether the specified file can be used with AndroidFs::show_view_file_dialog.

§Args
  • uri :
    Target file uri.
    This needs to be readable.
§Support

All Android version.

Source

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

Take persistent permission to access the file, directory and its descendants.
This is a prolongation of an already acquired permission, not the acquisition of a new one.

This works by just calling, without displaying any confirmation to the user.

Note that there is a limit to the total number of URI that can be made persistent by this function.
Therefore, it is recommended to relinquish the unnecessary persisted URI by AndroidFs::release_persisted_uri_permission or AndroidFs::release_all_persisted_uri_permissions.
Persisted permissions may be relinquished by other apps, user, or by moving/removing entries. So check by AndroidFs::check_persisted_uri_permission.
And you can retrieve the list of persisted uris using AndroidFs::get_all_persisted_uri_permissions.

§Args
§Support

All Android version.

Source

fn check_persisted_uri_permission( &self, uri: &FileUri, mode: PersistableAccessMode, ) -> Result<bool>

Check a persisted URI permission grant by AndroidFs::take_persistable_uri_permission.
Returns false if there are only non-persistent permissions or no permissions.

§Args
  • uri :
    URI of the target file or directory.

  • mode :
    The mode of permission you want to check.

§Support

All Android version.

Source

fn get_all_persisted_uri_permissions( &self, ) -> Result<impl Iterator<Item = PersistedUriPermission>>

Return list of all URI permission grants that have been persisted by AndroidFs::take_persistable_uri_permission.

§Support

All Android version.

Source

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

Relinquish a persisted URI permission grant by AndroidFs::take_persistable_uri_permission.

§Args
  • uri :
    URI of the target file or directory.
§Support

All Android version.

Source

fn release_all_persisted_uri_permissions(&self) -> Result<()>

Relinquish a all persisted uri permission grants by AndroidFs::take_persistable_uri_permission.

§Support

All Android version.

Source

fn is_visual_media_dialog_available(&self) -> Result<bool>

Verify whether AndroidFs::show_open_visual_media_dialog is available on a given device.

§Support

All Android version.

Source

fn private_storage(&self) -> &impl PrivateStorage<R>

File storage intended for the app’s use only.

Source

fn public_storage(&self) -> &impl PublicStorage<R>

File storage that is available to other applications and users.

Source

fn app_handle(&self) -> &AppHandle<R>

Provided Methods§

Source

fn is_available(&self) -> bool

Verify whether this plugin is available.

On Android, this returns true.
On other platforms, this returns false.

Source

fn get_metadata(&self, uri: &FileUri) -> Result<Metadata>

Queries the file system to get information about a file, directory.

§Args
  • uri :
    Target URI.
    This needs to be readable.
§Note

This uses AndroidFs::open_file internally.

§Support

All Android version.

Source

fn read(&self, uri: &FileUri) -> Result<Vec<u8>>

Reads the entire contents of a file into a bytes vector.

If you need to operate the file, use AndroidFs::open_file instead.

§Args
  • uri :
    Target file URI.
    This needs to be readable.
§Support

All Android version.

Source

fn read_to_string(&self, uri: &FileUri) -> Result<String>

Reads the entire contents of a file into a string.

If you need to operate the file, use AndroidFs::open_file instead.

§Args
  • uri :
    Target file URI.
    This needs to be readable.
§Support

All Android version.

Source

fn write(&self, uri: &FileUri, contents: impl AsRef<[u8]>) -> Result<()>

Writes a slice as the entire contents of a file.
This function will entirely replace its contents if it does exist.

If you want to operate the file, use AndroidFs::open_file instead.

§Args
  • uri :
    Target file URI.
    This needs to be writable.
§Support

All Android version.

Source

fn write_via_kotlin( &self, uri: &FileUri, contents: impl AsRef<[u8]>, ) -> Result<()>

Writes a slice as the entire contents of a file.
This function will entirely replace its contents if it does exist.

Differences from std::fs::File::write_all is the process is done on Kotlin side.
See AndroidFs::open_file for why this function exists.

If AndroidFs::write is used, it automatically fall back to this by AndroidFs::need_write_via_kotlin, so there should be few opportunities to use this.

If you want to write using std::fs::File, not entire contents, use AndroidFs::write_via_kotlin_in.

§Inner process

The contents is written to a temporary file by Rust side and then copied to the specified file on Kotlin side by AndroidFs::copy_via_kotlin.

§Support

All Android version.

Source

fn write_via_kotlin_in<T>( &self, uri: &FileUri, contents_writer: impl FnOnce(&mut File) -> Result<T>, ) -> Result<T>

See AndroidFs::write_via_kotlin for information.
Use this if you want to write using std::fs::File, not entire contents.

If you want to retain the file outside the closure, you can perform the same operation using AndroidFs::copy_via_kotlin and PrivateStorage. For details, please refer to the internal implementation of this function.

§Args
  • uri :
    Target file URI to write.

  • contetns_writer :
    A closure that accepts a mutable reference to a std::fs::File and performs the actual write operations. Note that this represents a temporary file.

Source

fn need_write_via_kotlin(&self, uri: &FileUri) -> Result<bool>

Determines if the file needs to be written via Kotlin side instead of Rust side.
Currently, this returns true only if the file is on GoogleDrive.

§Support

All Android version.

Source

fn show_open_dir_dialog(&self) -> Result<Option<FileUri>>

👎Deprecated: Confusing name. Please use show_manage_dir_dialog instead.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§