简体   繁体   中英

Cannot write External Storage in folder Download - Android

I'm new in android and sometimes I can't find the right solution and this is one of it.

I wrote a simple app to write internal pdf generated using ITextPdf libray. This is worked fine and I can see pdf file from Device File Explorer. Now I'm making the same thing using external storage, but in this case I can't generate file in Download folder. I found out solutions that for my code don't work.

My code:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-sdk android:minSdkVersion="21"
        android:targetSdkVersion="31"
        android:maxSdkVersion="31" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.PDFApplication">
        <activity
            android:name=".PdfDocumentTestActivity"
            android:exported="true" />
        <activity
            android:name=".MainActivity"
            android:exported="true" />
        <activity
            android:name=".SavePathActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

File.java

public class SavePathActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_save_path);

        Button btnShowPath = findViewById(R.id.btnPath);
      
        btnShowPath.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    writeFile();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private boolean isExternalStorageWritable(){

        String res = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
            Log.i("State","it's writable");
            return true;
        }else{
            return false;
        }
    }

    public void writeFile() throws FileNotFoundException {

        if (isExternalStorageWritable() && checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
       //if (isExternalStorageWritable()) {
            String directory_path = Environment.getExternalStorageDirectory() + "/MyDir/";
            String targetPdf = directory_path + "ITEXTPDF.pdf";

            Rectangle layout = new Rectangle(PageSize.ARCH_A);
            //layout.setBackgroundColor(new BaseColor(100, 200, 180)); //Background color
            layout.setBorderColor(BaseColor.DARK_GRAY);  //Border color
            layout.setBorderWidth(6);      //Border width
            layout.setBorder(Rectangle.BOX);

            Document document = new Document(layout);
            PdfWriter writer = null;

            File dir = new File(directory_path);
            if(!dir.exists())
                dir.mkdirs();

            File file = new File(dir, "newFile.pdf");
            FileOutputStream fOut = new FileOutputStream(file);
            try {
                try {
                    writer = PdfWriter.getInstance(document, fOut);
                } catch (DocumentException e) {
                    e.printStackTrace();
                }
                document.open();
                PdfContentByte cb = writer.getDirectContent();
                //Get width and height of whole page
                float pdfPageWidth = document.getPageSize().getWidth();
                float pdfPageHeight = document.getPageSize().getHeight();

                document.add(new Paragraph("pdfPageWidth = "+pdfPageWidth));
                document.add(new Paragraph("pdfPageHeight = "+pdfPageHeight));

                Barcode39 barcode39 = new Barcode39();
                barcode39.setCode("123456789");
                Image code39Image = barcode39.createImageWithBarcode(cb, null, null);
                document.add(code39Image);
                document.newPage();
                document.close();
                //viewPdf("newFile.pdf", "MyDir");
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(getApplicationContext(), "Cannot write External Storage", Toast.LENGTH_SHORT).show();
        }
    }


    public boolean checkPermission(String permission){
        int check = ContextCompat.checkSelfPermission(getApplicationContext(), permission);
        int pm = PackageManager.PERMISSION_GRANTED;
        return (check == PackageManager.PERMISSION_GRANTED);
    }
}

I found the problem in ContextCompat.checkSelfPermission(getApplicationContext(), permission) . It returns -1, but I can't understand doesn't work.

This for the internal storege. How you can see the app works设备文件资源管理器

In Android Q (Api-Level 29) you can not get this permission anymore:

https://developer.android.com/reference/android/Manifest.permission#WRITE_EXTERNAL_STORAGE

You need to work with the DocumentsFile API or other methods to write files there. Do not try to work with requestLegacyExternalStorage as it is not supported in Android 11 already.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM