首页 > 解决方案 > 使用 Raw 文件夹中存在的 adobe reader 打开 pdf

问题描述

我试图显示存在于 android studio 的 raw 文件夹中的 pdf 文件。我按照下面的代码。但这显示错误 android.content.ActivityNotFoundException: No Activity found to handle Intent 如何解决这个问题?

    String uri = "raw://" + R.raw.science;
    Uri path = Uri.fromFile(new File(String.valueOf(uri)));
    Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
    pdfIntent.setDataAndType(path, "application/pdf");
    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(pdfIntent);

标签: android

解决方案


首先:将您的 pdf 从 raw 复制到 sd 卡。
确保在 sd 卡中复制 pdf 的权限:
WRITE_EXTERNAL_STORAGE
READ_EXTERNAL_STORAGE

示例代码:

public static String dirPath = Environment.getExternalStorageDirectory() + "/ExampleDir/";
@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 CopyPDFFromAssets();
}

做一个方法:CopyPDFFromAssets()

 private void CopyPDFFromAssets() {
  copyFile(getResources().openRawResource(R.raw.science),
   new FileOutputStream(new File(dirPath, "my_pdf.pdf")));

  File pdfFile = new File(dirPath, "my_pdf.pdf");
  Uri path = Uri.fromFile(pdfFile);
  Intent intent = new Intent(Intent.ACTION_VIEW);
  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  intent.setDataAndType(path, "application/pdf");

  try {
   startActivity(intent);
  } catch (ActivityNotFoundException e) {
   Toast.makeText(this, "No Application Available to View PDF",
    Toast.LENGTH_SHORT).show();
  }

 } catch (Exception ex) {
  ex.toString();
 }

 }

然后创建方法copyFile()::

private void copyFile(InputStream in , OutputStream out) throws IOException {
 try {
  byte[] buffer = new byte[1024];
  int read;
  while ((read = in .read(buffer)) != -1) {
   out.write(buffer, 0, read);
  }
 } catch (Exception exp) {

 }    
}

推荐阅读