讀取並開啟assets下面的pdf檔案
總體流程:
Android不能直接開啟pdf檔案,無論是伺服器端的還是本地的,都不可直接開啟,在此主要介紹,開啟放在assets下的pdf檔案:
Android不可直接開啟assets下的pdf檔案,這就需要先從assets讀取到記憶體中,然後儲存到本地,再開啟本地的pdf檔案即可,話不多說看程式碼:
//從assets 資料夾中獲取檔案並讀取資料
public File getFromAssets(String fileName,File file){
String result = "";
OutputStream out = null;
try {
in = getResources().getAssets().open(fileName);
out=new FileOutputStream(file);
int lenght = in.available();
//建立byte陣列
byte[] buffer = new byte[lenght];
int bytes= in.read(buffer);
//.getString(buffer, ENCODING);
//將讀取的資料寫到本地
out.write(buffer, 0, bytes);
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
file.delete();
}finally{
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
}
}
}
return file;
}
});
// 開啟PDF檔案
private String reportUrl = "file:///android_asset/happywinner.pdf";
private String urlName = "happywinner.pdf";
((TextView) findViewById(R.id.freego_reader_pdf))
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String path = Environment
.getExternalStorageDirectory()
+ "/Download/";
String[] splitStrings = reportUrl.split("/");
String[] nameStrings = splitStrings[splitStrings.length - 1]
.split(".pdf");
String fileName = nameStrings[0] + ".pdf";
File file = new File(path + fileName);
Uri path1 = Uri.fromFile(getFromAssets(urlName,file));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setDataAndType(path1, "applicationf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
LifeHappyWinnerOnlineInsuranceActivity.this
.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(
LifeHappyWinnerOnlineInsuranceActivity.this,
"開啟失敗", 1);
}
}