我试图在单击按钮时选择PDF文件,但出现错误

时间:2019-12-13 13:36:34

标签: java android

我试图在单击按钮时选择PDF文件,但在三星设备上收到以下消息:

  

与该操作相关的所有应用已被关闭阻止或   没有安装。

private void selectPDFFiles(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                Uri.parse("package:" + getPackageName()));
        startActivity(intent);
        return;
    }
    intent = new Intent();
    intent.setType("application/pdf");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    startActivityForResult(Intent.createChooser(intent,"select PDF "), 1);
}

1 个答案:

答案 0 :(得分:1)

尝试下面的代码

private void selectPDFFiles(){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent.setType("application/pdf");
    startActivityForResult(intent, 555);
}

您可以在活动结果中获取文件

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case 555:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file
            Uri uri = data.getData();
            String uriString = uri.toString();
            File myFile = new File(uriString);
            String path = myFile.getAbsolutePath();
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

更新

也尝试下面的代码

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("application/pdf");
startActivityForResult(intent, 555);

希望这对您有帮助!

谢谢。