Android pdf viewer在android studio应用问题说明详解
之前一直是做.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应用问题说明详解,希望对大家有所帮助