我想通过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平板电脑上打开文件,但是当我运行我的程序打开它时,我收到错误:
打开文档时发生错误。
谁能告诉我哪里出错了?
答案 0 :(得分:3)
试试这个:
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) {
}
}
}
});
希望这会对你有所帮助。