[英]Android open pdf file via Intent
我在sdcard的某些文件夾中有一些pdf文件。 我創建了一個將所有pdf顯示為ListView的應用程序。 當我單擊任何pdf文件時,它在OfficeSuite應用程序中給出了錯誤(未支持的文件格式或錯誤的文件格式。代碼有問題。這是代碼。
//顯示為ListVIew的項目的代碼
ListView lv;
ArrayList<String> FilesInFolder = GetFiles(Environment.getExternalStorageDirectory()
+ "/SOMEFOLDER");
lv = (ListView) findViewById(R.id.filelist);
lv.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, FilesInFolder));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Clicking on items
open_File();
}
});
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyReports = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i=0; i<files.length; i++)
MyReports.add(files[i].getName());
}
return MyReports;
}
//通過VIA Intent打開文件的代碼
public void open_File(){
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/SOMEFOLDER");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent1 = Intent.createChooser(intent, "Open With");
try {
startActivity(intent1);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
錯誤:
文件格式損壞或不受支持
我認為您忘記了指定文件。 查看您的代碼,您僅將其指向文件夾,而沒有指向文件本身。 我認為這就是為什么它告訴您格式錯誤的原因,因為它不以.pdf結尾
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "SOMEFOLDER" + File.separator + "pdffile.pdf");
編輯:根據您的評論修改方法
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Clicking on items
String fileName = FilesInFolder.get(position);
open_File(fileName);
}
});
public void open_File(String filename){
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/SOMEFOLDER", filename);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent1 = Intent.createChooser(intent, "Open With");
try {
startActivity(intent1);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.