Android 11 crashes when sharing file

Asked

Viewed 77 times

0

I always shared files via my app, but with the version of android 11 I could not perform this process anymore, because the file in question will not. I tried using Fileprovide as per the documentation but error return: (java.lang.Illegalargumentexception: Failed to find configured root that contains /Storage/Emulated/0/Download/Teste2.txt). I have tried several ways checking several suggestions and so far I could not and decided to ask for help.

Androidmanifest.xml

<xml version=1.0 encoding=utf-8>
<manifest xmlns:android='http://schemas.android.com/apk/res/android'
    xmlns:dist="http://schemas.android.com/apk/distribution"
    package="com.login.projetobase">

    <dist:module dist:instant="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:restoreNeedsApplication="true">


        <!-- android.support.v4.content.FileProvider  / androidx.core.content.FileProvider -->
         <provider
          android:name="androidx.core.content.FileProvider"
          android:authorities="com.login.projetobase.FileProvider"
          android:exported="false"
          android:grantUriPermissions="true" >
          <meta-data
              android:name="android.support.FILE_PROVIDER_PATHS"
              android:resource="@xml/provider_paths" />
          </provider>



        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

    <!-- GRUPO STORAGE -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />
</manifest>

provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path
        name="Download"
        path="/" />
</paths> 

Mainactivity.java

public class MainActivity extends Activity {

    String P_ACTIVITY = "MainActivity";
    util utl = new util();
    String ativa_log = "S";

    File sdcard_sdk29;
    private static java.io.File sdcard;


    Button btn ;


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

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

        btn.setOnClickListener(new View.OnClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.Q)
            public void onClick(View v) {
                utl.PRINT_LOG(1, P_ACTIVITY+"btn.setOnClickListener-> **** INICIOU ****", ativa_log);
                COMPARTILHA();

            }
        });

    }




    public void COMPARTILHA() {
        try {
            utl.PRINT_LOG(2, P_ACTIVITY + " COMPARTILHA() ...... INICIADO", ativa_log);

            String NOME_ARQ = "Teste2.txt";
            String texto = "Teste de compartilhamento";
            File arq;
            byte[] dados;


            String RAIZ3 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();

            // CRIA O ARQUIVO NA PASTA DOWNLOAD
            arq = new File(RAIZ3 , NOME_ARQ);
            utl.PRINT_LOG(2, P_ACTIVITY + " COMPARTILHA()-> DIRETORIO  = ["+RAIZ3.toString()+"]", ativa_log);
            FileOutputStream fos;
            dados = texto.getBytes();
            fos = new FileOutputStream(arq);
            fos.write(dados);
            fos.flush();
            fos.close();

           //INICIANDO O PROCESSO DE COMPARTILHAR AQUIVO
            //Uri arquivo = Uri.fromFile(arq);
            //Uri arquivo2 = Uri.parse(arq.toString());

            Context context = getApplicationContext();
            Uri contentUri = FileProvider.getUriForFile(context, "com.login.projetobase.FileProvider", arq);

            utl.PRINT_LOG(2, P_ACTIVITY + " COMPARTILHA2()-> CAMINHO URI = ["+contentUri.toString()+"]", ativa_log);
            utl.PRINT_LOG(2, P_ACTIVITY + " COMPARTILHA2()-> processando.....", ativa_log);


            final Intent _intent = new Intent();
            _intent.setAction(Intent.ACTION_SEND);
            _intent.setType("application/pdf");
            _intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION|Intent.FLAG_GRANT_READ_URI_PERMISSION);
            _intent.putExtra(Intent.EXTRA_TEXT, "Compartilhamento com anexo");
            _intent.putExtra(Intent.EXTRA_TITLE, "Teste de Compartilhamento");
            _intent.putExtra(Intent.EXTRA_STREAM,  contentUri);
            startActivity(Intent.createChooser(_intent, "Compartilhar"));

        } catch (Exception e) {
            utl.PRINT_LOG(3, P_ACTIVITY + " ERRO->"+e, ativa_log);
            Toast.makeText(getApplication(), "ERRO="+e, Toast.LENGTH_LONG).show();

        }
    }



}
  • On Android 11 it is not possible to access the internal or external storage, only the app data directory, to access the storage must use Scoped Storage or can include the premise: android.permission.MANAGE_EXTERNAL_STORAGE however this premise is only attributed to apps that demonstrate need and have to be authorized by Google to be published in the Play Store

  • Good morning Tiago Oliveira, thank you for the help and dedication of your time in helping me! I made an adjustment in the provider_paths.xml file where <Files-path was to <External-path and ran the above code. But I also put the permission that spoke on my Androidmanisfest android.permission.MANAGE_EXTERNAL_STORAGE, permission I do not know yet inform if what made it work was the permission or adjustment that inform, So I’m going to run some more tests and I’m going to inform you here to help other people who have experienced the same difficulty that I have here. Thanks in advance attention and time of help

  • Android is supposed to block any path that is not on "/data/user/0/app.package.name/", without that premise is not supposed to work, if the goal is to publish on the playstore, you should use Scoped Storage, since the revisions of apps (at this date) is suspended, to get a input stream or output stream can follow my answer in this question https://stackoverflow.com/questions/62899773/saving-binary-files-with-scoped-storage

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.