国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > 综合技术 > android-pdf-viewer在android studio应用问题说明

android-pdf-viewer在android studio应用问题说明

来源:程序员人生   发布时间:2016-10-12 09:09:26 阅读次数:3248次

android-pdf-viewer在android studio利用问题说明

小白1枚,之前1直是做.NET开发的,最近需要弄1个新闻app,能力有限,只能借助HTML5 WebAPP+android studio来完成这项工作。
android studio主要用WebView来加载发布好的WebApp,打包生产APP。
其中由于显示1些pdf文档,所以研究了1下,记录1下心得,同时也希望帮助到新手们。

android 显示网络pdf,基本原理:先将pdf文件通过DownloadManager下载得手机sdk某个文件夹中,然后通过android-pdf-viewer插件进行显示。

android-pdf-viewer插件可以直接到github上下载,地址:https://github.com/barteksc/AndroidPdfViewer
或直接到发布好的页面下载:https://github.com/barteksc/AndroidPdfViewer/releases
我下载的是:AndroidPdfViewer⑵.1.0版本zip包

将下载AndroidPdfViewer⑵.1.0包解压出来,再你的app项目中,打开 File -> New -> Import Module 选择到刚才解压的文件夹

本人目录是:D:\AndroidStudioProjects\AndroidPdfViewer⑵.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,实现了接收另外1个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⑴]; 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 + "-"); } } } }
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生