在我的軟體中,用戶資訊串列以 PDF 檔案的形式離線生成。我在 Android 7 和 8 上測驗了這個操作,一切都很好。但是當我在 Android 11 上測驗時,沒有生成該檔案。我一直在尋找解決方案,但我并沒有真正找到該領域的完整資源和培訓。
我可以通過 Intent 創建一個 PDF 檔案,但是在另一個軟體中,我看到只要單擊保存按鈕,就會在 Documents 檔案夾中創建一個具有程式名稱的檔案夾,并在其中創建檔案。
這是我用來將 PDF 檔案保存在下載檔案夾中的代碼,它適用于 Android 7 和 8。
public void savePdfFileToStorage(String pdfTitleHeader, String currentTime, PdfDocument pdfDocument, Context context) {
String PdfDir=Environment.getExternalStorageDirectory() "/Download/Apple";
File dir=new File(PdfDir);
if (!dir.exists())
dir.mkdir();
String fileName = pdfTitleHeader "_" todayDate() "_" convertToEnglishDigits(currentTime) ".pdf";
File file = new File(PdfDir,fileName);
if (!file.exists()) {
try {
file.createNewFile();
Log.e(TAG, "savePdfFileToStorage: " "file created" file.getName() "path: " file.getPath());
} catch (IOException e) {
e.printStackTrace();
}
}
try {
pdfDocument.writeTo(new FileOutputStream(file));
Log.e(TAG, "savePdfFileToStorage: pdf Wrote in file");
Toast.makeText(context, "???? PDF ?? ???? Download/Apple ????? ????? ????? ??.", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "???? PDF ????? ???.", Toast.LENGTH_LONG).show();
}
pdfDocument.close();
}
我將這些代碼寫在 Manifest 檔案中。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application>
...
android:requestLegacyExternalStorage="true"
...
</application>
請告知我應該在哪里添加代碼來解決 Android 11 中的存盤問題。
uj5u.com熱心網友回復:
此代碼生成類似名稱:allTransaction 20220202 10:15:23 .pdf
:是檔案名和路徑中的禁止字符。
uj5u.com熱心網友回復:
我使用了以下代碼,終于能夠將檔案保存在 Documents 檔案夾中。
public void savePdfFileToStorage(String pdfTitleHeader, String currentTime, PdfDocument pdfDocument, Context context) {
File dir;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) "/Apple");
else dir = new File(Environment.getExternalStorageDirectory() "/Apple");
if (!dir.exists())
if(!dir.mkdir())
return;
String fileName = pdfTitleHeader "_" todayDate() "_" convertToEnglishDigits(currentTime) ".pdf";
File file = new File(dir, fileName);
if (!file.exists()) {
try {
file.createNewFile();
Log.e(TAG, "savePdfFileToStorage: " "file created" file.getName() "path: " file.getPath());
} catch (IOException e) {
e.printStackTrace();
}
}
try {
pdfDocument.writeTo(new FileOutputStream(file));
Log.e(TAG, "savePdfFileToStorage: pdf Wrote in file");
Toast.makeText(context, "???? PDF ?? ???? Download/Apple????? ????? ????? ??.", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "???? PDF ????? ???.", Toast.LENGTH_LONG).show();
}
pdfDocument.close();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/441143.html
