簡體   English   中英

無法在文件夾中寫入外部存儲下載 - Android

[英]Cannot write External Storage in folder Download - Android

我是 android 的新手,有時我找不到合適的解決方案,這就是其中之一。

我寫了一個簡單的應用程序來編寫使用 ITextPdf 庫生成的內部 pdf。 這工作正常,我可以從設備文件資源管理器中看到 pdf 文件。 現在我正在使用外部存儲做同樣的事情,但在這種情況下,我無法在下載文件夾中生成文件。 我發現了對我的代碼不起作用的解決方案。

我的代碼:

<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>

文件.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);
    }
}

我在ContextCompat.checkSelfPermission(getApplicationContext(), permission)中發現了問題。 它返回-1,但我不明白不起作用。

這用於內部存儲。 如何查看應用程序的工作原理設備文件資源管理器

在 Android Q(Api-Level 29)中,您無法再獲得此權限:

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

您需要使用 DocumentsFile API 或其他方法在其中寫入文件。 不要嘗試使用 requestLegacyExternalStorage,因為 Android 11 已經不支持它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM