@@ -9,6 +9,62 @@ use tokio::sync::watch::{Receiver, channel};
99
1010use crate :: { StorageBacking , StorageSubscriber , serde_to_string, try_serde_from_string} ;
1111
12+ /// Get the default data directory for the current platform.
13+ ///
14+ /// # Example
15+ /// ```rust
16+ /// use dioxus_sdk_storage::{data_directory, set_dir};
17+ ///
18+ /// // Set the storage directory to a folder named "my_app" in the default data directory.
19+ /// set_dir!(data_directory().join("my_app"));
20+ /// ```
21+ pub fn data_directory ( ) -> std:: path:: PathBuf {
22+ #[ cfg( target_os = "android" ) ]
23+ {
24+ android_data_directory ( )
25+ }
26+
27+ #[ cfg( not( target_os = "android" ) ) ]
28+ {
29+ directories:: BaseDirs :: new ( )
30+ . unwrap ( )
31+ . data_local_dir ( )
32+ . to_path_buf ( )
33+ }
34+ }
35+
36+ #[ cfg( target_os = "android" ) ]
37+ fn android_data_directory ( ) -> std:: path:: PathBuf {
38+ use jni:: JNIEnv ;
39+ use jni:: objects:: { JObject , JString } ;
40+ use std:: sync:: mpsc:: channel;
41+
42+ let ( tx, rx) = channel ( ) ;
43+
44+ dioxus:: mobile:: wry:: prelude:: dispatch (
45+ move |env : & mut JNIEnv , activity : & JObject , _webview| {
46+ let files_dir = env
47+ . call_method ( activity, "getFilesDir" , "()Ljava/io/File;" , & [ ] )
48+ . unwrap ( )
49+ . l ( )
50+ . unwrap ( ) ;
51+
52+ let abs_path = env
53+ . call_method ( files_dir, "getAbsolutePath" , "()Ljava/lang/String;" , & [ ] )
54+ . unwrap ( )
55+ . l ( )
56+ . unwrap ( ) ;
57+
58+ let abs_path: JString = abs_path. into ( ) ;
59+ let abs_path: String = env. get_string ( & abs_path) . unwrap ( ) . into ( ) ;
60+
61+ tx. send ( std:: path:: PathBuf :: from ( abs_path) ) . unwrap ( ) ;
62+ } ,
63+ ) ;
64+
65+ rx. recv ( ) . unwrap ( )
66+ }
67+
1268#[ doc( hidden) ]
1369/// Sets the directory where the storage files are located.
1470pub fn set_directory ( path : std:: path:: PathBuf ) {
@@ -17,12 +73,7 @@ pub fn set_directory(path: std::path::PathBuf) {
1773
1874#[ doc( hidden) ]
1975pub fn set_dir_name ( name : & str ) {
20- set_directory (
21- directories:: BaseDirs :: new ( )
22- . unwrap ( )
23- . data_local_dir ( )
24- . join ( name) ,
25- )
76+ set_directory ( data_directory ( ) . join ( name) )
2677}
2778
2879/// The location where the storage files are located.
0 commit comments