2012-05-10 26 views
34

Tôi đang cố gắng khởi chạy Intent để mở tệp pdf bên trong thư mục nội dung trong ứng dụng của mình. Tôi đã đọc hàng tá bài đăng nhưng vẫn bị kẹt. Rõ ràng tôi cần phải sao chép pdf vào thẻ sd đầu tiên sau đó khởi động một Intent. Nó vẫn không hoạt động.Cách mở tệp PDF qua Intent từ thẻ SD

Tôi nghĩ vấn đề là Intent tung ra vì vậy tôi chỉ đơn giản là cố gắng để mở một tập tin "example.pdf" mà tôi đã copy vào thẻ SD sử dụng mã này:

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(); 
} 

Đây là sản lượng LogCat của tôi .

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 

Trừ khi mã này được chạy, tôi nhận được Toast sau (không sản xuất bởi ứng dụng của tôi)

"Không phải là một loại tài liệu được hỗ trợ"

Nhưng tôi có thể mở tài liệu bằng tay thông qua Đã cài đặt ứng dụng xem PDF. Bất cứ sự giúp đỡ nào cũng được đánh giá cao.

Trả lời

96

Hãy thử mã này, tập tin hiển thị pdf Từ/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); 
+2

Cảm ơn bạn đã kết thúc tìm kiếm của mình. Tại sao điều đó làm việc thay vì phân tích cú pháp url từ một String? –

+1

Tôi làm cách nào để chuyển sang trang cụ thể trực tiếp? Không có cách nào khác ư? –

+0

@PratikButani - Khi bạn đang sử dụng ứng dụng pdf của bên thứ ba để mở tệp pdf, bạn không thể xử lý điều hướng trang trong pdf cho bất kỳ trang cụ thể nào. – user370305

0

Nó có thể có cái gì để làm với thực tế rằng các tập tin trong thư mục tài sản được nén.

Hãy thử di chuyển nó vào thư mục res/raw/ của bạn. Thông tin

thêm: https://stackoverflow.com/a/4432804/413127

+0

Tôi thậm chí không cố xem pdf cho ứng dụng của mình nữa. Tôi đã sử dụng hệ điều hành của mình để sao chép bản pdf vào sdcard và tôi vẫn không thể xem nó qua Mục đích –

3

Tải về mã nguồn từ đây (Open pdf file from sdcard in android programmatically)

Thêm sự phụ thuộc này:

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&#8221; 
xmlns:tools=”http://schemas.android.com/tools&#8221; 
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&#8221; 
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:

gói 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 + “-“); 
} 
} 
} 
} 

Cảm ơn!

0

Đối với Android Nougat trở lên phiên bản Android, một số công việc khác phải được thực hiện nếu không ứng dụng sẽ không thể mở tệp .pdf.Chúng tôi phải đặt quyền tạm thời cho URI bằng cách sử dụng FileProvider

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 
    File file=new File(mFilePath); 
    Uri uri = FileProvider.getUriForFile(this, getPackageName() + ".provider", file); 
    intent = new Intent(Intent.ACTION_VIEW); 
    intent.setData(uri); 
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 
    startActivity(intent); 
    } else { 
    intent = new Intent(Intent.ACTION_VIEW); 
    intent.setDataAndType(Uri.parse(mFilePath), "application/pdf"); 
    intent = Intent.createChooser(intent, "Open File"); 
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    startActivity(intent); 
    } 
Các vấn đề liên quan