我已经测试了您的代码,它在 Android 10 设备上运行良好。您缺少以下内容:
1.在Android Manifest File中添加READ_EXTERNAL_STORAGE权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
并在应用程序标签内将 requestLegacyExternalStorage 添加到 true 以便能够访问 Android 10 及更高版本设备上的外部存储。
<application
android:requestLegacyExternalStorage="true"
2.验证设备上“/Download/Pdfs/myfile.pdf”路径下的pdf是否存在。
3.通过在运行时首先在 onCreate 方法中请求外部存储权限,使用以下代码更改您的活动:
public class PdfViewActivity2 extends AppCompatActivity {
private static final int READ_STORAGE_PERMISSION_REQUEST_CODE = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//check if Read External Storage permission was granded
boolean granded = checkPermissionForReadExtertalStorage();
if(!granded){
requestPermissionForReadExtertalStorage();
}
else {
readPdf();
}
}
public boolean checkPermissionForReadExtertalStorage() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int result = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED;
}
return false;
}
public void requestPermissionForReadExtertalStorage() {
try {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_STORAGE_PERMISSION_REQUEST_CODE);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case READ_STORAGE_PERMISSION_REQUEST_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Read Pdf from External Storage
readPdf();
} else {
// permission denied. Disable the functionality that depends on this permission.
}
}
}
}
private void readPdf(){
File path = new File(Environment.getExternalStorageDirectory().getPath() + "/Download/Pdfs/myfile.pdf");
PDFView pdfView = findViewById(R.id.pdfView);
pdfView.fromFile(path).load();
}
}