使用Intent显示PDF文件选择

时间:2017-07-24 10:56:24

标签: java android pdf android-intent

以下代码显示了所有文件,但我选择了另一个格式文件,它返回错误。

Intent selectionintent = new Intent(Intent.ACTION_GET_CONTENT);
            selectionintent.setType("application/pdf");
            selectionintent.addCategory(Intent.CATEGORY_OPENABLE);
            PackageManager packageManager = getPackageManager();

            List activitiesPDF = packageManager.queryIntentActivities(selectionintent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            boolean isIntentSafePDF = activitiesPDF.size() > 0;
            if (isIntentSafePDF)
                startActivityForResult(selectionintent, CODE_RESULT);
            else
                Toast.makeText(UpdateFileActivity.this, "Only select pdf files", Toast.LENGTH_SHORT).show();

onActivity结果:

 if (requestCode == CODE_RESULT && resultCode == RESULT_OK) {
        Uri uri = data.getData();
        String file = uri.toString();
        File f = new File(file);
        if (file.startsWith("content://")) {
            Cursor cursor = null;
            try {
                cursor = getContentResolver().query(uri, null, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                }
            } finally {
                cursor.close();
            }
        } else if (file.startsWith("file://")) {
            displayName = f.getName();
        }
        filetext.setText(displayName);
    }

我想只显示pdf文件

1 个答案:

答案 0 :(得分:2)

从移动设备获取pdf文件列表(我使用了意图,但没有获得所有的pdf文件,所以我使用了这种方法)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    boolean result = marshMallowPermission.checkPermissionForReadExtertalStorage();
    if (result) {
        getPdfFromExternalStorage(Environment.getExternalStorageDirectory());
    } else {
        try {
            marshMallowPermission.requestPermissionForReadExtertalStorage();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
} else {
    getPdfFromExternalStorage(Environment.getExternalStorageDirectory());
}

从设备

搜索pdf文件
private void getPdfFromExternalStorage(File folder) {
    if (folder != null) {
        if (folder.listFiles() != null) {
            for (File file : folder.listFiles()) {
                if (file.isFile()) {
                    //.pdf files
                    if (file.getName().contains(".pdf")) {
                        Log.d("filePath-------", "" + file.getPath());
                    }
                } else {
                    getPdfFromExternalStorage(file);
                }
            }
        }
    }
}