Android Kotlin code for Create folder With Real-Time Permissions
To create folder programmatically in android need runtime permissions in Android using Kotlin.
First you have to create New Android Project
Then steps as follow:
In AndroidManifest.xml file you have to add code:
<!-- Permission required for the Android 11 (R) and above -->
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
......
android:requestLegacyExternalStorage="true">
Create activity: MainActivity.ktWrite below code:private const val TAG = "PermissionCheck"
private const val STORAGE_PERMISSION_CODE = 100
class MainActivity : AppCompatActivity() {
lateinit var binding:ActivityMainBinding
private val storagePermissionsArray = arrayOf(
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
android.Manifest.permission.CAMERA
)
private fun checkArrayStoragePermissions(): Boolean {
for (permission in storagePermissionsArray) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
return false
}
}
return true
}
var permissionGrant=false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.getRoot())
//init UI Views
if(checkReadWritePermission()){
permissionGrant=true
}else{
requestCallPermission()
}
//handle click, create folder
binding.btnCreateFolder.setOnClickListener {
if (permissionGrant){
val folderName = binding.etFolderName.text.toString().trim()
if(folderName.isEmpty()){
toast("Please provide folder name")
return@setOnClickListener
}
createNewFolder()
}
else{
requestCallPermission()
}
}
}
private fun createNewFolder(){
//folder name
val folderName = binding.etFolderName.text.toString().trim()
//create folder using name we just input
if(folderName.isEmpty()){
return
}
val folderCreate = File("${Environment.getExternalStorageDirectory()}/$folderName")
if(folderCreate.exists() && folderCreate.isDirectory()){
toast("Folder already exist")
}else{
//create folder
val folderCreated = folderCreate.mkdir()
//show if folder created or not
if (folderCreated) {
Log.d("nipaerror",folderCreate.absolutePath)
toast("Folder Path: ${folderCreate.absolutePath}")
} else {
toast("Folder not created. Try again")
}
}
}
private fun requestCallPermission(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
//Android is 11(R) or above
try {
val intent = Intent()
intent.action = Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION
val uri = Uri.fromParts("package", this.packageName, null)
intent.data = uri
sdkUpperActivityResultLauncher.launch(intent)
}
catch (e: Exception){
Log.e(TAG, "error ", e)
val intent = Intent()
intent.action = Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION
sdkUpperActivityResultLauncher.launch(intent)
}
}else{
//for below version
ActivityCompat.requestPermissions(this,
arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE),
STORAGE_PERMISSION_CODE
)
}
}
private val sdkUpperActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
//here we will handle the result of our intent
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
//Android is 11(R) or above
if (Environment.isExternalStorageManager()){
//Manage External Storage Permission is granted
Log.d(TAG, "Manage External Storage Permission is granted")
createNewFolder()
}
else{
//Manage External Storage Permission is denied....
Log.d(TAG, "Permission is denied")
toast("Manage External Storage Permission is denied....")
}
}
}
private fun checkReadWritePermission(): Boolean{
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
//Android is 11(R) or above
Environment.isExternalStorageManager()
}
else{
//Permission is below 11(R)
// checkBelowPermissionGranted()
checkArrayStoragePermissions()
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == STORAGE_PERMISSION_CODE){
if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }){
Log.d(TAG, "External Storage Permission granted")
permissionGrant=true
createNewFolder()
}
else{
//External Storage Permission denied...
Log.d(TAG, "Some Permission denied...")
toast("Some Storage Permission denied...")
}
}
}
private fun toast(message: String){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}and in xml page Add code:<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/etFolderName"
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:layout_height="wrap_content"
android:hint="Enter Folder Name..."/>
<!--Button: Create folder-->
<com.google.android.material.button.MaterialButton
android:id="@+id/btnCreateFolder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Create Folder"/>
</LinearLayout>if you need full code please click on :https://github.com/nipamaity/CreateFolderWithPermission
if any other help is needed please comments
Comments
Post a Comment