Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android pdf viewer在android studio應用問題說明詳解

Android pdf viewer在android studio應用問題說明詳解

編輯:關於Android編程

之前一直是做.NET開發的,最近需要弄一個新聞app,能力有限,只能借助HTML5 WebAPP+android studio來完成這項工作。
android studio主要用WebView來加載發布好的WebApp,打包生產APP。

其中由於顯示一些pdf文檔,所以研究了一下,記錄一下心得,同時也希望幫助到新手們。

android 顯示網絡pdf,基本原理:先將pdf文件通過DownloadManager下載到手機sdk某個文件夾中,然後通過android-pdf-viewer插件進行顯示。

android-pdf-viewer插件可以直接到github上下載,地址:https://github.com/barteksc/AndroidPdfViewer
或者直接到發布好的頁面下載:https://github.com/barteksc/AndroidPdfViewer/releases
我下載的是:AndroidPdfViewer-2.1.0版本zip包

將下載AndroidPdfViewer-2.1.0包解壓出來,再你的app項目中,打開 File -> New -> Import Module 選擇到剛才解壓的文件夾

本人目錄是:D:\AndroidStudioProjects\AndroidPdfViewer-2.1.0\android-pdf-viewer

這裡寫圖片描述 

完成後,回提示先ERROR:

Error:Plugin with id ‘com.github.dcendents.android-maven' not found.

解決方法:

點擊你的工程Gradle Scripts目錄下的bulid.gradle (Project:你的工程名)

buildscript { 
repositories { 
jcenter() 
} 
dependencies { 
classpath ‘com.android.tools.build:gradle:2.0.0' 
} 
}

中dependencies的下添加 classpath ‘com.github.dcendents:android-maven-gradle-plugin:1.3',

Mark Modules之後,出現新的ERROR:

Error:Plugin with id ‘com.jfrog.bintray' not found.

此時同樣在dependencies下添加:classpath “com.jfrog.bintray.gradle:gradle-bintray-plugin:1.0”

再次Mark Modules就不會報錯了。

先就可以開始使用 android-pdf-viewer 插件了,

別忘記引用權限問題哦

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"/>
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />

先代碼為項目中report activity.java,實現了接收另外一個activity跳轉過來同時傳遞參數pdf地址,然後通過DownloadManager下載完成之後,顯示pdf。

package cn.cgrs.myphone;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.OpenableColumns;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;
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.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
public class Report extends AppCompatActivity implements OnPageChangeListener, OnLoadCompleteListener {
private com.github.barteksc.pdfviewer.PDFView pdfView ;
private TextView textView;
private DownloadManager downloadManager;
private SharedPreferences prefs;
private static String DL_ID = "downloadId";
Integer pageNumber = 0;
String pdfFileName = "yyy.pdf";
Uri uri;
String AUrl;
private Boolean isDown = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report);
Intent intent = getIntent(); // 獲取 Intent
AUrl = intent.getStringExtra("url"); // 獲取 String 值
Log.e("接收url:",AUrl);
//AUrl = "http://www.tyyq.cn/xhsapp/download/a03790b7f27243eeada01537a2ce2f77.pdf";
String[] exts = AUrl.split("/");
pdfFileName = exts[exts.length-1];
Log.e("pdf文件名:",pdfFileName);
String pdfName = Environment.getExternalStorageDirectory() +
"/download";
File file = new File(pdfName, pdfFileName);
pdfView = (com.github.barteksc.pdfviewer.PDFView)findViewById(R.id.pdfView);
textView = (TextView) findViewById(R.id.textView);
if(file.exists()){
Log.e("Tip:","報告已經存在!");
//文件已經存在,則直接顯示
uri = Uri.fromFile(file);
displayFromUri(uri);
textView.setVisibility(View.GONE);
pdfView.setVisibility(View.VISIBLE);
}
else{
isDown = true;
}
//Log.e("prefs字符串:",prefs.toString());
}
@Override
protected void onResume(){
super.onResume();
if(isDown)
{
try{
Log.e("Tip:","報告不存在,需要下載!");
DL_ID = pdfFileName;
//文件不存在需要先下載
downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
StartReport();
}
catch (Exception ex)
{
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//unregisterReceiver(receiver);
try {
unregisterReceiver(receiver);
} catch (IllegalArgumentException e) {
if (e.getMessage().contains("Receiver not registered")) {
// Ignore this exception. This is exactly what is desired
} else {
// unexpected, re-throw
throw e;
}
}
}
//下載報告啟動函數
protected void StartReport() {
// TODO Auto-generated method stub
if(!prefs.contains(DL_ID) || true) { //
// String url = AUrl;
//Log.e("-----",AUrl);
//String[] exts = url.split("/");
//pdfFileName = "97b49c0822c14a01b3ebc273679bc6bf.pdf";
//exts[exts.length-1];
String url = AUrl;//"http://www.tyyq.cn/RollImage/11.pdf";
Log.e("開始下載url:",AUrl);
//開始下載
Uri resource = Uri.parse(encodeGB(url));
DownloadManager.Request request = new DownloadManager.Request(resource);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
request.setAllowedOverRoaming(false);
//設置文件類型
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
request.setMimeType(mimeString);
//在通知欄中顯示
//設置通知欄標題
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.setDescription("輿情報告正在下載");
//request.setShowRunningNotification(true);
request.setVisibleInDownloadsUi(true);
//sdcard的目錄下的download文件夾
request.setDestinationInExternalPublicDir("/download/", pdfFileName);
request.setTitle("輿情報告");
long id = downloadManager.enqueue(request);
//保存id
prefs.edit().putLong(DL_ID, id).commit();
} else {
Log.e("提示:","下載已經開始,檢查狀態");
//下載已經開始,檢查狀態
queryDownloadStatus();
}
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
/**
* 如果服務器不支持中文路徑的情況下需要轉換url的編碼。
* @param string
* @return
*/
public String encodeGB(String string)
{
//轉換中文編碼
String split[] = string.split("/");
for (int i = 1; i < split.length; i++) {
try {
split[i] = URLEncoder.encode(split[i], "GB2312");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
split[0] = split[0]+"/"+split[i];
}
split[0] = split[0].replaceAll("\\+", "%20");//處理空格
return split[0];
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//這裡可以取得下載的id,這樣就可以知道哪個文件下載完成了。適用與多個下載任務的監聽
Log.v("intent", ""+intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0));
queryDownloadStatus();
}
};
private void queryDownloadStatus() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(prefs.getLong(DL_ID, 0));
Cursor c = downloadManager.query(query);
if(c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch(status) {
case DownloadManager.STATUS_PAUSED:
Log.v("down", "STATUS_PAUSED");
case DownloadManager.STATUS_PENDING:
Log.v("down", "STATUS_PENDING");
case DownloadManager.STATUS_RUNNING:
//正在下載,不做任何事情
Log.v("down", "STATUS_RUNNING");
break;
case DownloadManager.STATUS_SUCCESSFUL:
//完成
Log.v("down", "下載完成");
String pdfName = Environment.getExternalStorageDirectory() +
"/download";
File file = new File(pdfName, pdfFileName);
uri = Uri.fromFile(file);
Log.e("----",uri.toString());
displayFromUri(uri);
textView.setVisibility(View.GONE);
pdfView.setVisibility(View.VISIBLE);
break;
case DownloadManager.STATUS_FAILED:
//清除已下載的內容,重新下載
Log.v("down", "STATUS_FAILED");
downloadManager.remove(prefs.getLong(DL_ID, 0));
prefs.edit().clear().commit();
break;
}
}
}
/*pdf顯示函數集合*/
private void displayFromUri(Uri urii) {
//pdfFileName = getFileName(urii);
pdfView.fromUri(urii)
.defaultPage(pageNumber)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
public void onResult(int resultCode, Intent intent) {
if (resultCode == RESULT_OK) {
uri = intent.getData();
displayFromUri(uri);
}
}
@Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
}
public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
if (result == null) {
result = uri.getLastPathSegment();
}
return result;
}
@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 + "-");
}
}
}
}

以上所述是小編給大家介紹的Android pdf viewer在android studio應用問題說明詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對本站網站的支持!

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved