简体   繁体   English

无法在文件夹中写入外部存储下载 - Android

[英]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.我是 android 的新手,有时我找不到合适的解决方案,这就是其中之一。

I wrote a simple app to write internal pdf generated using ITextPdf libray.我写了一个简单的应用程序来编写使用 ITextPdf 库生成的内部 pdf。 This is worked fine and I can see pdf file from Device File Explorer.这工作正常,我可以从设备文件资源管理器中看到 pdf 文件。 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文件.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) .我在ContextCompat.checkSelfPermission(getApplicationContext(), permission)中发现了问题。 It returns -1, but I can't understand doesn't work.它返回-1,但我不明白不起作用。

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:在 Android Q(Api-Level 29)中,您无法再获得此权限:

https://developer.android.com/reference/android/Manifest.permission#WRITE_EXTERNAL_STORAGE 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.您需要使用 DocumentsFile API 或其他方法在其中写入文件。 Do not try to work with requestLegacyExternalStorage as it is not supported in Android 11 already.不要尝试使用 requestLegacyExternalStorage,因为 Android 11 已经不支持它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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