파일 권한 얻기
둘러보기로 이동
검색으로 이동
파일 권한 얻기
AndroidManifest.xml
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
build.gradle.kts
buildFeatures {
buildConfig = true
}
1. Check if permission is already granted Before attempting file operations, verify if your app has the special access using Environment.isExternalStorageManager().
import android.os.Environment
import android.os.Build
private fun hasAllFilesAccess(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { // R is API 30 (Android 11)
Environment.isExternalStorageManager()
} else {
// For devices below Android 11, traditional permissions apply
// You would check READ/WRITE_EXTERNAL_STORAGE here
true // Or implement a check for the older permissions
}
}
2. Request the permission If access is not granted, launch an intent to the system settings page where the user can manually enable the permission for your app.
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import androidx.activity.result.contract.ActivityResultContracts
// Register an Activity Result Launcher to handle the result when the user returns from settings
private val storagePermissionResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
// When the user returns from the settings screen, check the permission status again
if (hasAllFilesAccess()) {
// Permission granted, proceed with your file operations
println("All files access granted!")
} else {
// Permission denied, handle accordingly (e.g., show a dialog)
println("All files access denied.")
}
}
private fun requestAllFilesAccess() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
val uri = Uri.fromParts("package", packageName, null)
intent.data = uri
storagePermissionResultLauncher.launch(intent)
}
// No runtime request needed for versions below Android 11
}
3. Integrate into your Activity
Call these functions within your Activity (e.g., in onCreate or when a specific button is clicked):
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (!hasAllFilesAccess()) {
requestAllFilesAccess()
} else {
// Permission already granted, perform file operations
}
}
// ... include hasAllFilesAccess() and requestAllFilesAccess() functions here ...
}