Accessing the /sdcard
directory (or external storage in general) in Android requires special permissions and considerations due to security and privacy restrictions. Here's how you can do it:
Request Permissions:
Starting with Android 6.0 (API level 23), you need to request runtime permissions for accessing external storage. You can add the following permissions to yourAndroidManifest.xml
:xml复制代码<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
However, keep in mind that
WRITE_EXTERNAL_STORAGE
is deprecated in Android 10 (API level 29) and no longer required for scoped storage access. If you target Android 10 or higher, consider using scoped storage or MediaStore API for file access.To request permissions at runtime, you can use
ActivityCompat.requestPermissions()
.Use Scoped Storage or MediaStore:
If your app targets Android 10 (API level 29) or higher, it's recommended to use scoped storage or the MediaStore API to access files on external storage. Scoped storage limits your app's access to files that it has created or files that the user has explicitly shared with your app using a file chooser or intent.Scoped Storage: Your app can access its own app-specific directory on external storage without any special permissions. To access other directories, you need to use
Storage Access Framework
(SAF) orMediaStore
API.MediaStore API: This API allows you to access media files (photos, videos, audio) shared by users and stored in the public directories on external storage.
Using Environment Class:
If your app targets Android 9 (API level 28) or lower, you can still access the/sdcard
directory using theEnvironment
class. Here's an example:java复制代码File sdcard = Environment.getExternalStorageDirectory(); File file = new File(sdcard, "yourfile.txt"); // Then you can use file for reading or writing try { // Example: Writing to the file FileOutputStream fos = new FileOutputStream(file); fos.write("Hello, World!".getBytes()); fos.close(); } catch (IOException e) { e.printStackTrace(); }
Note: This approach is not recommended for apps targeting Android 10 or higher due to the introduction of scoped storage.
Handle Permissions Results:
When you request permissions at runtime, you need to handle the results in anonRequestPermissionsResult
callback. This callback is invoked when the user responds to the permission request dialog.Test on Real Devices:
Always test your app on real devices with different Android versions to ensure that file access works as expected.
Remember that the /sdcard
path is a legacy path that might not always exist on all devices or Android versions. Always use the Environment
class or scoped storage/MediaStore APIs to access external storage.
评论