我正在尝试启动Intent
以在我的应用中的资源文件夹中打开pdf。我已经阅读了几十篇帖子,但仍然被卡住了。显然我需要先将pdf复制到SD卡然后再启动Intent
。它仍然无效。
我认为问题是Intent
启动,所以我只是试图打开一个文件“example.pdf”,我使用这段代码将其复制到SD卡上:
Log.w("IR", "TRYING TO RENDER: " + Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf"), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
Log.e("IR", "No exception");
}
catch (ActivityNotFoundException e) {
Log.e("IR", "error: " + e.getMessage());
Toast.makeText(InvestorRelations.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
这是我的LogCat输出。
05-10 10:35:10.950: W/IR(4508): TRYING TO RENDER: /mnt/sdcard/example.pdf
05-10 10:35:10.960: E/IR(4508): No exception
除非运行此代码,否则我会收到以下Toast(不是由我的应用程序生成)
“不支持的文档类型”
但我可以通过安装的PDF查看应用程序手动打开文档。任何帮助都将非常感激。
答案 0 :(得分:117)
尝试此代码,显示pdf文件来自/ sdcard
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
答案 1 :(得分:3)
从此处下载源代码(Open pdf file from sdcard in android programmatically)
添加此依赖项:
compile ‘com.github.barteksc:android-pdf-viewer:2.0.3’
<强> activity_main.xml中:强>
<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:id=”@+id/activity_main”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background=”#efefef”>
<ListView
android:layout_width=”match_parent”
android:id=”@+id/lv_pdf”
android:divider=”#efefef”
android:layout_marginLeft=”10dp”
android:layout_marginRight=”10dp”
android:layout_marginTop=”10dp”
android:layout_marginBottom=”10dp”
android:dividerHeight=”5dp”
android:layout_height=”wrap_content”>
</ListView>
</RelativeLayout>
<强> MainActivity.java:强>
package com.pdffilefromsdcard;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra(“position”, i);
startActivity(intent);
Log.e(“Position”, i + “”);
}
});
}
public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
getfile(listFile[i]);
} else {
boolean booleanpdf = false;
if (listFile[i].getName().endsWith(“.pdf”)) {
for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
} else {
}
}
if (booleanpdf) {
booleanpdf = false;
} else {
fileList.add(listFile[i]);
}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
} else {
Toast.makeText(getApplicationContext(), “Please allow the permission”, Toast.LENGTH_LONG).show();
}
}
}
}
<强> activity_pdf.xml:强>
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:background=”#ffffff”
android:layout_height=”match_parent”
android:orientation=”vertical”>
<com.github.barteksc.pdfviewer.PDFView
android:id=”@+id/pdfView”
android:layout_margin=”10dp”
android:layout_width=”match_parent”
android:layout_height=”match_parent” />
</LinearLayout>
<强> PdfActivity.java:强>
package com.pdffilefromsdcard;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;
import java.io.File;
import java.util.List;
public class PdfActivity extends AppCompatActivity implements OnPageChangeListener,OnLoadCompleteListener {
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG=”PdfActivity”;
int position=-1;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}
private void init(){
pdfView= (PDFView)findViewById(R.id.pdfView);
position = getIntent().getIntExtra(“position”,-1);
displayFromSdcard();
}
private void displayFromSdcard() {
pdfFileName = MainActivity.fileList.get(position).getName();
pdfView.fromFile(MainActivity.fileList.get(position))
.defaultPage(pageNumber)
.enableSwipe(true)
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
@Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format(“%s %s / %s”, pdfFileName, page + 1, pageCount));
}
@Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), “-“);
}
public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {
Log.e(TAG, String.format(“%s %s, p %d”, sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + “-“);
}
}
}
}
谢谢!
答案 2 :(得分:1)
现在接受的答案已经过时了。将FileProvider用于file sharing。
答案 3 :(得分:1)
此代码允许从您的SD卡中提取pdf文件
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent, 200);
答案 4 :(得分:0)