[英]Pdf file is not opening in Android
我想在單擊“ pdfButton”時打開一個pdf文件(可在Android手機的“下載”文件夾中找到)。執行該操作時,什么也沒有發生,沒有記錄錯誤或顯示了pdf文件。 有人可以幫忙嗎?
package com.mycompany.myfirstglapp;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceView;
import android.webkit.WebView;
import android.widget.Toast;
import java.io.File;
/**
* Created by admin on 1/11/2016.
*/
public class PdfActivity extends Activity {
private SurfaceView surface;
Button pdfButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
surface = (SurfaceView) findViewById(R.id.pdfSurface);
pdfButton = (Button) findViewById(R.id.pdfView);
pdfButton .setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// On click will call the showPdf method to display the pdf file in sd card or downloads
showPdf(view);
}
});
}
public void showPdf(View view) {
// The pdf file [LawsofthegamewebEN_Neutral.pdf] is avaialble in Android > Downloads folder.
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/LawsofthegamewebEN_Neutral.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) {
Toast.makeText(PdfActivity.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
}
}
如果您使用調試器逐步執行代碼,或放入更多日志記錄語句,我懷疑您會發現file.exists()
返回false
。 而且,在這種情況下,您現在什么也不做。
我想打開一個pdf文件(可在Android手機的“下載”文件夾中找到)
那不是您的代碼正在尋找的地方。 更換:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/LawsofthegamewebEN_Neutral.pdf");
與:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "LawsofthegamewebEN_Neutral.pdf");
還要注意,您的file.exists()
調用意味着您將需要擁有READ_EXTERNAL_STORAGE
權限。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.