之前一直是做.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 插件了,
别忘记引用权限问题哦
先代码为项目中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(Listtree, 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应用问题说明详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!