Android 6.0 Permissions Why when I try to create a folder in the SDcard I create it in the internal storage of the device?

2

First of all I clarify that I am a novice in programming. What I'm trying to do is create a simple folder in the sdcard, but I create it in the internal storage of the device. To do these tests I am using my own Smartphone which is an LG G4 H815 with android 6.0. The app consists of a button, that when pressed creates a folder with the name "PruebaMermisMM". When I start the app apparently everything works fine, I request permission to access photos and multimedia files on the device, but I create it as I said earlier in the internal storage.

In the manifest I have:

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

In build.gradle (Module: app) I have:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "lucasandroid.pruebapermisosmm"
        minSdkVersion 18
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'
    testCompile 'junit:junit:4.12'
}

The java code is:

package lucasandroid.pruebapermisosmm;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity {

private static final int CODIGO_SOLICITUD_PERMISO=123;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn=(Button)findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(checkearPermiso()){
                //Nuestra app tiene permiso
                crearCarpeta();

            }else{
                //Nuestra app no tiene permiso, entonces debo solicitar el mismo
                solicitarPermiso();
            }
        }
    });
}

private boolean checkearPermiso(){


    //Array de permisos
    String[] permisos={Manifest.permission.WRITE_EXTERNAL_STORAGE};

    for(String perms:permisos){
        int res=checkCallingOrSelfPermission(perms);
        if(!(res== PackageManager.PERMISSION_GRANTED)){
            return false;
        }
    }
    return true;

}

private void solicitarPermiso(){

    String[] permisos={Manifest.permission.WRITE_EXTERNAL_STORAGE};

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){         //Verificamos si la version de android del dispositivo es mayor
       requestPermissions(permisos,CODIGO_SOLICITUD_PERMISO);  //o igual a MarshMallow
    }

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    boolean autorizado= true;   //Si el permiso fue autorizado

    switch (requestCode){
        case CODIGO_SOLICITUD_PERMISO:
            for(int res:grantResults){

                //si el usuario concedió todos los permisos
                autorizado= autorizado && (res == PackageManager.PERMISSION_GRANTED);
            }
            break;

        default:
            //Si el usuario autorizó los permisos
            autorizado= false;
            break;
    }

    if(autorizado){
        //Si el usuario autorizó todos los permisos podemos ejecutar nuestra tarea
        crearCarpeta();
    }else {
        //Se debe alertar al usuario que los permisos no han sido concedidos
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if(shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
                Toast.makeText(MainActivity.this,"Los permisos de almacenamiento externo fueron denegados",Toast.LENGTH_SHORT).show();
            }
        }
    }
}

private void crearCarpeta(){

    File file= new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"PruebaPermisosMM"); // Creamos un archivo llamado PruebaPermisosMM


    //Verificamos si el archivo fue creado exitosamente

    if(!file.exists()) {
        boolean ff = file.mkdir();
        if (ff){
            Toast.makeText(MainActivity.this,"La carpeta fue creada exitosamente",Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(MainActivity.this,"La carpeta no pudo ser creada",Toast.LENGTH_SHORT).show();
        }
    }else{
        Toast.makeText(MainActivity.this,"La carperta ya existe",Toast.LENGTH_SHORT).show();
    }

}
}

I also clarify that when I use the same permission request code for the use of the camera or audio recorder through Intent, it works well for me. I do not know why I have problems reading or writing in the sd.

    
asked by Lucas 12.04.2017 в 20:14
source

1 answer

1

You comment that you create it in the internal storage, but you are using it:

Environment.getExternalStorageDirectory()

In this part of your code, therefore you should be creating the file or directory in the external storage:

 File file= new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"PruebaPermisosMM"); // Creamos un archivo llamado PruebaPermisosMM
  

getExternalStorageDirectory () : Returns the directory of   shared storage / external main.

If you want to get the internal storage path instead, you would use getFilesDir ()

The question would be what is the reason why you consider that you are creating the directory in the internal storage of the device?

I advise you to read the documentation: Internal storage or external

    
answered by 12.04.2017 в 22:47