初学andriod,项目 target API :31
在manifest中:
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
在MainActivity.kt中:
class MainActivity : ComponentActivity() {
@RequiresApi(Build.VERSION_CODES.R)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ActivityCompat.requestPermissions(this, arrayOf(
Manifest.permission.MANAGE_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
), 1)
var customers = arrayOf(
Customer("张三", "123", "张三店铺", "cc"),
Customer("李四","5656","李四店铺","dd")
)
// val vals = ContentValues()
// vals.put(MediaStore.Files.FileColumns.DISPLAY_NAME, "customer.json")
// vals.put(MediaStore.Files.FileColumns.MIME_TYPE, "text/plain")
// vals.put(MediaStore.Files.FileColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS)
// val uri = contentResolver.insert(MediaStore.Files.getContentUri("external"), vals)
// if (uri != null) {
// val outStream = contentResolver.openOutputStream(uri)
// if(outStream != null){
// outStream.write(Gson().toJson(customers).toByteArray())
// outStream.close()
// }
// }
FileWriter(Environment.getDataDirectory().name + "\\" + "customer.json").use { w -> w.write(Gson().toJson(customers)) }
setContent {
//...
}
}
使用FileWriter报错:
java.io.FileNotFoundException: data\customer.json (Read-only file system)
使用OutputStream报错:
java.lang.SecurityException: Permission Denial: writing com.android.providers.media.MediaProvider uri content://media/external/file from pid=6532, uid=10063 requires android.permission.WRITE_EXTERNAL_STORAGE, or grantUriPermission()