之前一直是做.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;@OverrIDeprotected voID onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentVIEw(R.layout.activity_report);Intent intent = getIntent(); // 获取 IntentAUrl = 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());}@OverrIDeprotected 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();}}}@OverrIDeprotected voID onPause() {// Todo auto-generated method stubsuper.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-throwthrow e;}}}//下载报告启动函数protected voID StartReport() {// Todo auto-generated method stubif(!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);//保存IDprefs.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() {@OverrIDepublic 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);}}@OverrIDepublic 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);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;}@OverrIDepublic 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应用问题说明详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程小技巧网站的支持!
总结以上是内存溢出为你收集整理的Android pdf viewer在android studio应用问题说明详解全部内容,希望文章能够帮你解决Android pdf viewer在android studio应用问题说明详解所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)