android
[android]Scoped Storage(SAF)
pearlab
2023. 12. 19. 13:30
fun createExtenalUrl(resultLauncher: ActivityResultLauncher<Intent>){
val filename = "test.pcm"
val saf = SAFManager()
val uriSeparator = "%2F"
val path = "test${uriSeparator.toString()}sub"
saf.oepnExplore(path, filename, resultLauncher)
}
fun onActivityResult(activityesult: ActivityResult, activity: AppCompatActivity){
println("[File]onActivityResult(${activityesult.resultCode})")
println("[File]onActivityResult(${activityesult.data?.data})")
if (activityesult.resultCode == AppCompatActivity.RESULT_OK) {
activityesult.data?.data?.let {
try {
// val ofs = activity.contentResolver.openOutputStream(it as Uri)
// ofs?.writer()
// ofs?.close()
} catch (e: Exception) {
ALOG.e("[File]onActivityResult(${activityesult.data})")
e.printStackTrace()
}
}
}
}
package com.selvy.srclientsamplek.util
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.DocumentsContract
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
class SAFManager{
val TAG = this.javaClass.simpleName
fun oepnExplore(path:String, filename:String, resultLauncher:ActivityResultLauncher<Intent>){
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "application/*"
flags = Intent.FLAG_GRANT_WRITE_URI_PERMISSION
putExtra(Intent.EXTRA_TITLE, filename)
//[Todo] target {path} "content://com.android.externalstorage.documents/document/primary%3A{path}"
val uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3A$path")
ALOG.i(TAG, String.format("[File]path(path)"))
ALOG.i(TAG, String.format("[File]path_uri(${uri.path})"))
// val file = File("/sdcard/Documents/")
// val docFile = DocumentFile.fromFile(file)
// ALOG.i(TAG, String.format("[File]path_uri(${docFile.uri})"))
putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri)
}
resultLauncher.launch(intent)
// val intentA = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
// val file = File(Environment.getExternalStorageDirectory().getPath() + File.separator + "AWav/test_stt_kor1.pcm")
// val docFile = DocumentFile.fromFile(file)
// ALOG.i(TAG, String.format("[File]path_uri(${docFile.uri})"))
// val uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3Alogs%2F")
// type = "application/*"
// putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri)
// }
// resultLauncher.launch(intentA)
}
}