微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法在 android 11 中写入和打开文件

如何解决无法在 android 11 中写入和打开文件

在我的应用程序中,按钮事件从服务器返回 PDF 的 base64 字符串。然后我将此 base64 写入文件。并尝试通过外部 PDF 查看器打开它。它在 Android 11 以外的 Android 设备上运行良好。请参阅下面的代码

 byte[] decodedContent = android.util.Base64.decode(base64.getBytes(),Base64.DEFAULT);

                try {
                    File path = new File(getApplicationContext().getExternalFilesDir(null).getAbsolutePath(),"PDFData");
                    if (!path.exists()) {
                        path.mkdirs();
                    }
                    file = new File(path,"myPDF.pdf");


                    outputStream = new FileOutputStream(file);
                    outputStream.write(decodedContent);
                    outputStream.close();
                    Uri targetUri = Uri.fromFile(file);

                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(targetUri,"application/pdf");
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    PackageManager pm = getApplicationContext().getPackageManager();
                    if (pm.resolveActivity(intent,PackageManager.MATCH_DEFAULT_ONLY) == null) {
                        Toast.makeText(getApplicationContext(),"No application found to open PDF,please install one.",Toast.LENGTH_SHORT).show();
                    }
                    else{
                        startActivity(intent);
                    }
                } catch (FileNotFoundException ex) {
                    ex.printstacktrace();
                    Log.d("FileNotFound","FileNotFoundException");
                } catch (IOException ex) {
                    ex.printstacktrace();
                    Log.d("IOException","IOException");

                } finally {
                    // Make absolutely certain the outputStream is closed
                    try {
                        Log.d("outputStream","outputStream");

                        if (outputStream != null) {
                            outputStream.close();
                        }
                    } catch (IOException ex) {
                        ex.printstacktrace();
                    }

清单文件中已包含以下权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 

请帮我解决这个问题。提前致谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。