【问题标题】:Android select PDF using Intent on API 18Android 使用 API 18 上的 Intent 选择 PDF
【发布时间】:2015-11-20 20:01:49
【问题描述】:

我正在使用以下代码使用Intent 选择 PDF 文件。它在 Android 5.0+ 上完美运行,但 API 18 上没有合适的应用程序打开 PDF 文件消息。

public static Intent pickPdf() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/pdf");
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    return intent;
}

startActivityForResult(Intent.createChooser(pickPdf(), "Open with"), PICK_PDF);

【问题讨论】:

  • Android 中没有内置任何东西必须处理该 MIME 类型的 Intent 操作。
  • @CommonsWare 如果你想从存储中选择一个使用Intent的PDF文件,你会怎么做?
  • 回退显示您自己选择的 UI(使用MediaStore 查找所有application/pdf 文件,显示在ListViewRecyclerView 中)。

标签: android pdf android-intent


【解决方案1】:

正如@CommonsWare 所建议的那样——不能保证安装了处理 PDF 的应用程序。

我之前解决这个问题的方法是使用App Chooser,如下所示:

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

Intent intent = Intent.createChooser(target, "Open File");
try {
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    // Instruct the user to install a PDF reader here, or something
    ShowToast(TAG, "Unable to open PDF. Please, install a PDF reader app.");
}   

【讨论】:

  • 我不想打开特定的 PDF 文件,我只需要从存储中选择它并在 onActivityResultmethod 上获取它的 URI。
【解决方案2】:

您可以尝试使用此代码从存储中选择 pdf 并获取 URI

private static final int PICK_PDF = 123;

意图意图 = 新意图(Intent.ACTION_GET_CONTENT); intent.setType("应用程序/pdf"); startActivityForResult(intent, PICK_PDF);

把下面的代码放在onActivityResult中

if (requestCode == PICK_PDF && resultCode == Activity.RESULT_OK) {
        if (data == null) {
            //Display an error
            Toast.makeText(this, "something went wrong Retry", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            InputStream inputStream = getContentResolver().openInputStream(data.getData());
            Uri uri = data.getData();
            //here is the uri you can do what you want
            Log.e(TAG, "onActivityResult: " + uri);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(this, "Error:"+e.toString(), Toast.LENGTH_SHORT).show();
        }
     }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 2018-03-13
    相关资源
    最近更新 更多