我正在制作一个应用程序包含一些pdf文件,但我不知道我如何使用它 1-我应该在资源中复制我的pdf文件? (哪个文件夹?) 2-打开它需要什么代码? (需要在onClick方法中编写哪些代码?) 3-这个程序有哪些类和方法可供使用?
保留以下代码(它们用于忽略身体错误)
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);}
答案 0 :(得分:0)
如果您想从 webview 打开PDF,可以使用以下代码:
public class ActivityName extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView mWebView=new WebView(MyPdfViewActivity.this);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url="+LinkTo);
setContentView(mWebView);
}
}
如果您想在本地打开PDF,可以将其放在res / raw文件夹或assets文件夹中(在以下示例中使用assets文件夹)。然后,您需要使用以下代码在本地放置文件:
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getExternalFilesDir(null), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
然后,您可以使用以下代码访问PDF,同样假设用户安装了PDF查看器:
public class OpenPdf extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.OpenPdfButton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File file = new File("/sdcard/example.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(OpenPdf.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
如果您想从应用程序中打开它,可以尝试this