【问题标题】:How can I open a PDF file via my Android app?如何通过我的 Android 应用打开 PDF 文件?
【发布时间】:2012-07-10 16:44:46
【问题描述】:

我想通过 Android 应用打开一个 pdf 文件。到目前为止,我已经编写了以下代码:

public class PdfopenActivity extends Activity {
    String selectedFilePath;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btnOpen=(Button)findViewById(R.id.button1);

        btnOpen.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // Sample.pdf is my file name it is in /Root/Download/Sample.pdf 
                // path of the file

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

pdf 为 175kb,我可以直接在 Galaxy Tab2 平板电脑上打开该文件,但是当我运行我的程序打开它时出现错误:

打开文档时发生错误。

谁能告诉我哪里出错了?
.

【问题讨论】:

  • 两台设备都安装了相同的PDF查看器?
  • 确保 pdf 位于 sdcard 中的正确位置。如果它位于任何文件夹中,也将被包含在其中
  • 通过编写 Environment.getExternalStorageDirectory().getAbsolutePath()+"/Sample.pdf" 表明它不在任何文件夹中,而是在 sdcard 内
  • /Root/sdcard/Download/sample.pdf
  • 您必须将下载包含为 /sdcard/download/sample.pdf

标签: android android-intent path launching-application


【解决方案1】:

试试这个:

        Button btnOpen=(Button)findViewById(R.id.button1);
        btnOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = new File("/sdcard/sample.pdf");

                if (file.exists()) {
                    Uri path = Uri.fromFile(file);
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(path, "application/pdf");
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                    try {
                        startActivity(intent);
                    } 
                    catch (ActivityNotFoundException e) {

                    }
                }
            }
        });

希望这会对你有所帮助。

【讨论】:

  • 感谢您的回复,当我点击按钮时没有执行任何操作?
  • 我已经在你的问题下制作了 cmets 看到它
  • 感谢您的回复,我的 pdf 文件位置是 /Root/sdcard/Download/sample.pdf
猜你喜欢
  • 2021-03-22
  • 1970-01-01
  • 2014-06-08
  • 1970-01-01
  • 1970-01-01
  • 2019-05-13
  • 1970-01-01
  • 2013-07-01
  • 2014-07-11
相关资源
最近更新 更多