Commit d98d153d authored by 周文华's avatar 周文华

【修复&优化】1.修复部分pdf加载与显示逻辑问题。2.优化部分pdf显示加载逻辑。3.尝试修复内存溢出问题。

parent b6f77636
...@@ -35,3 +35,18 @@ ...@@ -35,3 +35,18 @@
java.lang.String getId(); java.lang.String getId();
boolean isLimitAdTrackingEnabled(); boolean isLimitAdTrackingEnabled();
} }
# 删除控制台日志打印
-assumenosideeffects class android.util.Log {
public static boolean isLoggable(java.lang.String, int);
public static int v(...);
public static int i(...);
public static int w(...);
public static int d(...);
public static int e(...);
}
-assumenosideeffects class java.io.PrintStream {
public *** println(...);
public *** print(...);
}
...@@ -32,7 +32,6 @@ import com.base.pdfviewerscannerwhite.ads.admob.AdmobInterstitialUtils ...@@ -32,7 +32,6 @@ import com.base.pdfviewerscannerwhite.ads.admob.AdmobInterstitialUtils
import com.base.pdfviewerscannerwhite.ads.admob.AdmobNativeUtils import com.base.pdfviewerscannerwhite.ads.admob.AdmobNativeUtils
import com.base.pdfviewerscannerwhite.bean.ConstObject.DO_SAVE_PDF import com.base.pdfviewerscannerwhite.bean.ConstObject.DO_SAVE_PDF
import com.base.pdfviewerscannerwhite.bean.ConstObject.haveGuideGesture import com.base.pdfviewerscannerwhite.bean.ConstObject.haveGuideGesture
import com.base.pdfviewerscannerwhite.bean.PdfPageBean
import com.base.pdfviewerscannerwhite.databinding.ActivityPdfBinding import com.base.pdfviewerscannerwhite.databinding.ActivityPdfBinding
import com.base.pdfviewerscannerwhite.helper.BaseActivity import com.base.pdfviewerscannerwhite.helper.BaseActivity
import com.base.pdfviewerscannerwhite.helper.MyApplication import com.base.pdfviewerscannerwhite.helper.MyApplication
...@@ -86,6 +85,7 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView { ...@@ -86,6 +85,7 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView {
super.onDestroy() super.onDestroy()
muPDFCore?.onDestroy() muPDFCore?.onDestroy()
AdmobNativeUtils.onDestroy() AdmobNativeUtils.onDestroy()
pdfPageAdapter.release()
} }
...@@ -108,7 +108,7 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView { ...@@ -108,7 +108,7 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView {
val file = File(path) val file = File(path)
binding.tvPdfName.text = file.name binding.tvPdfName.text = file.name
pdfPresenter = PdfPresenter(this, this) pdfPresenter = PdfPresenter(this)
initAdapter() initAdapter()
changeNormalUI() changeNormalUI()
...@@ -127,7 +127,9 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView { ...@@ -127,7 +127,9 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView {
pdfPresenter.password = pwd pdfPresenter.password = pwd
pdfPageAdapter.setPassword(pwd) pdfPageAdapter.setPassword(pwd)
createPdfUI() createPdfUI()
muPDFCore?.countPages()?.let { pdfPresenter.iniPdfPage(it) } muPDFCore?.countPages()?.let {
//pdfPresenter.iniPdfPage(it)
}
SpStringUtils.addSpString(LAST_VIEW_KEY, "${path}_/_${System.currentTimeMillis()}") SpStringUtils.addSpString(LAST_VIEW_KEY, "${path}_/_${System.currentTimeMillis()}")
} else { } else {
toast("unknown error") toast("unknown error")
...@@ -135,7 +137,9 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView { ...@@ -135,7 +137,9 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView {
} }
} else { } else {
createPdfUI() createPdfUI()
muPDFCore?.countPages()?.let { pdfPresenter.iniPdfPage(it) } muPDFCore?.countPages()?.let {
//pdfPresenter.iniPdfPage(it)
}
SpStringUtils.addSpString(LAST_VIEW_KEY, "${path}_/_${System.currentTimeMillis()}") SpStringUtils.addSpString(LAST_VIEW_KEY, "${path}_/_${System.currentTimeMillis()}")
} }
...@@ -347,7 +351,9 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView { ...@@ -347,7 +351,9 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView {
} }
private fun initAdapter() { private fun initAdapter() {
pdfPageAdapter = PdfPagerAdapter(path, uri) pdfPageAdapter = PdfPagerAdapter(path, uri){
iniSetVerticalSeekbar(it)
}
pdfPageAdapter.clickAction = { pageIndex -> pdfPageAdapter.clickAction = { pageIndex ->
binding.mupdfReaderView.displayedViewIndex = pageIndex binding.mupdfReaderView.displayedViewIndex = pageIndex
} }
...@@ -361,7 +367,8 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView { ...@@ -361,7 +367,8 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView {
isShowTopBottomLayout = false isShowTopBottomLayout = false
hideKeyboard(binding.editSearch) hideKeyboard(binding.editSearch)
val topAnim: Animation = TranslateAnimation(0f, 0f, 0f, -binding.vAnimatorTop.height.toFloat()) val topAnim: Animation =
TranslateAnimation(0f, 0f, 0f, -binding.vAnimatorTop.height.toFloat())
topAnim.setDuration(200) topAnim.setDuration(200)
topAnim.setAnimationListener(object : Animation.AnimationListener { topAnim.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {} override fun onAnimationStart(animation: Animation) {}
...@@ -372,7 +379,8 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView { ...@@ -372,7 +379,8 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView {
}) })
binding.vAnimatorTop.startAnimation(topAnim) binding.vAnimatorTop.startAnimation(topAnim)
val bottomAnim: Animation = TranslateAnimation(0f, 0f, 0f, binding.vAnimatorBottom.height.toFloat()) val bottomAnim: Animation =
TranslateAnimation(0f, 0f, 0f, binding.vAnimatorBottom.height.toFloat())
bottomAnim.duration = 200 bottomAnim.duration = 200
bottomAnim.setAnimationListener(object : Animation.AnimationListener { bottomAnim.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {} override fun onAnimationStart(animation: Animation) {}
...@@ -392,7 +400,8 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView { ...@@ -392,7 +400,8 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView {
if (!isShowTopBottomLayout) { if (!isShowTopBottomLayout) {
isShowTopBottomLayout = true isShowTopBottomLayout = true
val topAnim: Animation = TranslateAnimation(0f, 0f, -binding.vAnimatorTop.height.toFloat(), 0f) val topAnim: Animation =
TranslateAnimation(0f, 0f, -binding.vAnimatorTop.height.toFloat(), 0f)
topAnim.setDuration(200) topAnim.setDuration(200)
topAnim.setAnimationListener(object : Animation.AnimationListener { topAnim.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) { override fun onAnimationStart(animation: Animation) {
...@@ -405,7 +414,8 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView { ...@@ -405,7 +414,8 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView {
}) })
binding.vAnimatorTop.startAnimation(topAnim) binding.vAnimatorTop.startAnimation(topAnim)
val bottomAnim: Animation = TranslateAnimation(0f, 0f, binding.vAnimatorBottom.height.toFloat(), 0f) val bottomAnim: Animation =
TranslateAnimation(0f, 0f, binding.vAnimatorBottom.height.toFloat(), 0f)
bottomAnim.duration = 200 bottomAnim.duration = 200
bottomAnim.setAnimationListener(object : Animation.AnimationListener { bottomAnim.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) { override fun onAnimationStart(animation: Animation) {
...@@ -602,7 +612,8 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView { ...@@ -602,7 +612,8 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView {
fun switchOrientation() { fun switchOrientation() {
requestedOrientation = if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { requestedOrientation =
if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
} else { } else {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
...@@ -631,10 +642,4 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView { ...@@ -631,10 +642,4 @@ class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView {
const val SAVE_MODE_PAINTING_BRUSH = "Painting Brush" const val SAVE_MODE_PAINTING_BRUSH = "Painting Brush"
} }
override fun initPdfPageRv(items: List<PdfPageBean>) {
pdfPageAdapter.submitList(items)
pdfPageAdapter.changeSelectPager(0)
iniSetVerticalSeekbar(items.size)
}
} }
\ No newline at end of file
...@@ -7,7 +7,9 @@ import android.graphics.drawable.Drawable ...@@ -7,7 +7,9 @@ import android.graphics.drawable.Drawable
import android.net.Uri import android.net.Uri
import com.base.pdfviewerscannerwhite.helper.MyApplication.Companion.context import com.base.pdfviewerscannerwhite.helper.MyApplication.Companion.context
import com.base.pdfviewerscannerwhite.utils.LogEx import com.base.pdfviewerscannerwhite.utils.LogEx
import com.base.pdfviewerscannerwhite.utils.Paths
import com.base.pdfviewerscannerwhite.utils.UriUtils.readFileToByteArray import com.base.pdfviewerscannerwhite.utils.UriUtils.readFileToByteArray
import com.tom_roush.pdfbox.io.MemoryUsageSetting
import com.tom_roush.pdfbox.pdmodel.PDDocument import com.tom_roush.pdfbox.pdmodel.PDDocument
import com.tom_roush.pdfbox.pdmodel.PDPage import com.tom_roush.pdfbox.pdmodel.PDPage
import com.tom_roush.pdfbox.pdmodel.PDPageContentStream import com.tom_roush.pdfbox.pdmodel.PDPageContentStream
...@@ -25,38 +27,48 @@ import java.io.IOException ...@@ -25,38 +27,48 @@ import java.io.IOException
object PdfBoxUtils { object PdfBoxUtils {
private val TAG = "PdfUtils" private val TAG = "PdfUtils"
val memoryUsageSetting by lazy {
fun getNumberOfPages(filePath: String, password: String? = null, uri: String? = null): Int { // MemoryUsageSetting.setupMainMemoryOnly()
val document = // LogEx.logDebug("ttttttt","${Runtime.getRuntime().maxMemory() / 2}")
loadPDDocument(path = filePath, password, uri) MemoryUsageSetting.setupMixed(Runtime.getRuntime().maxMemory() / 2, 512 * 1024 * 1024)
val number = document.numberOfPages .also {
document.close() it.tempDir = Paths.cacheDir(Paths.PdfDir)
return number
} }
}
fun getPdfDrawablePage( fun getPdfDocument(
context: Context,
filePath: String, filePath: String,
password: String? = null, password: String? = null,
uri: String? = null, uri: String? = null,
): PDDocument {
return loadPDDocument(filePath, password, uri)
}
fun getPdfDrawablePage(
context: Context,
pageIndex: Int, pageIndex: Int,
scale: Float = 1f, scale: Float = 1f,
renderer: PDFRenderer,
): Drawable { ): Drawable {
val document = loadPDDocument(filePath, password, uri) val bitmap: Bitmap =
val renderer = PDFRenderer(document) renderer.renderImage(pageIndex, scale, ImageType.RGB, RenderDestination.EXPORT)
val bitmap: Bitmap = renderer.renderImage(pageIndex, scale, ImageType.RGB, RenderDestination.EXPORT)
val drawable = BitmapDrawable(context.resources, bitmap) val drawable = BitmapDrawable(context.resources, bitmap)
document.close()
return drawable return drawable
} }
fun checkPdfEncryption(filePath: String = "", uri: String? = null): Int { @Synchronized
fun checkPdfEncryption(
filePath: String = "",
uri: String? = null,
memUsageSetting: MemoryUsageSetting? = null
): Int {
var state = 0 var state = 0
var pdfDocument: PDDocument? = null var pdfDocument: PDDocument? = null
try { try {
pdfDocument = loadPDDocument(filePath, null, uri) pdfDocument =
loadPDDocument(filePath, null, uri, memUsageSetting ?: memoryUsageSetting)
pdfDocument.use { document -> pdfDocument.use { document ->
if (document.isEncrypted) { if (document.isEncrypted) {
println("The PDF is encrypted.") println("The PDF is encrypted.")
...@@ -80,7 +92,7 @@ object PdfBoxUtils { ...@@ -80,7 +92,7 @@ object PdfBoxUtils {
} }
} catch (e: IOException) { } catch (e: IOException) {
e.printStackTrace() e.printStackTrace()
state = 1 state = -1
} finally { } finally {
pdfDocument?.close() pdfDocument?.close()
} }
...@@ -171,19 +183,37 @@ object PdfBoxUtils { ...@@ -171,19 +183,37 @@ object PdfBoxUtils {
/** /**
* 注意一下PDDocument用完都要关闭一下 * 注意一下PDDocument用完都要关闭一下
*/ */
private fun loadPDDocument(path: String, password: String?, uri: String? = null): PDDocument { private fun loadPDDocument(
path: String,
password: String?,
uri: String? = null,
memUsageSetting: MemoryUsageSetting? = null
): PDDocument {
val memSet = memUsageSetting ?: MemoryUsageSetting.setupMainMemoryOnly()
return if (uri == null) { return if (uri == null) {
if (password == null) { if (password == null) {
PDDocument.load(File(path)) PDDocument.load(File(path), memSet)
} else { } else {
PDDocument.load(File(path), password) PDDocument.load(File(path), password, memSet)
} }
} else { } else {
if (password == null) { if (password == null) {
PDDocument.load(readFileToByteArray(context, Uri.parse(uri)) ?: byteArrayOf()) PDDocument.load(
readFileToByteArray(context, Uri.parse(uri)) ?: byteArrayOf(),
"",
null,
null,
memSet
)
} else { } else {
PDDocument.load(readFileToByteArray(context, Uri.parse(uri)) ?: byteArrayOf(), password) PDDocument.load(
readFileToByteArray(context, Uri.parse(uri)) ?: byteArrayOf(),
password,
null,
null,
memSet
)
} }
} }
} }
......
...@@ -2,10 +2,8 @@ package com.base.pdfviewerscannerwhite.ui.document.pdf ...@@ -2,10 +2,8 @@ package com.base.pdfviewerscannerwhite.ui.document.pdf
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.content.Context import android.content.Context
import android.net.Uri
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView.ViewHolder import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.base.pdfviewerscannerwhite.R import com.base.pdfviewerscannerwhite.R
import com.base.pdfviewerscannerwhite.bean.PdfPageBean import com.base.pdfviewerscannerwhite.bean.PdfPageBean
...@@ -13,15 +11,23 @@ import com.base.pdfviewerscannerwhite.databinding.ItemPdfPagerBinding ...@@ -13,15 +11,23 @@ import com.base.pdfviewerscannerwhite.databinding.ItemPdfPagerBinding
import com.base.pdfviewerscannerwhite.databinding.ItemPdfPagerSplitBinding import com.base.pdfviewerscannerwhite.databinding.ItemPdfPagerSplitBinding
import com.base.pdfviewerscannerwhite.utils.XmlEx.inflate import com.base.pdfviewerscannerwhite.utils.XmlEx.inflate
import com.chad.library.adapter4.BaseQuickAdapter import com.chad.library.adapter4.BaseQuickAdapter
import java.util.concurrent.LinkedBlockingQueue import com.tom_roush.pdfbox.pdmodel.PDDocument
import java.util.concurrent.ThreadPoolExecutor import com.tom_roush.pdfbox.rendering.PDFRenderer
import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class PdfPagerAdapter( class PdfPagerAdapter(
val pdfPath: String, val pdfPath: String,
val uri: String? = null, val uri: String? = null,
val itemLayout: Int = R.layout.item_pdf_pager, val itemLayout: Int = R.layout.item_pdf_pager,
private val previewScale: Float = 1f,
initCallBack: ((itemCount: Int) -> Unit)? = null
) : BaseQuickAdapter<PdfPageBean, PdfPagerAdapter.PdfPagerViewHolder>() { ) : BaseQuickAdapter<PdfPageBean, PdfPagerAdapter.PdfPagerViewHolder>() {
var mPassword: String? = null var mPassword: String? = null
...@@ -30,16 +36,94 @@ class PdfPagerAdapter( ...@@ -30,16 +36,94 @@ class PdfPagerAdapter(
inner class PdfPagerViewHolder(view: View) : ViewHolder(view) inner class PdfPagerViewHolder(view: View) : ViewHolder(view)
var corePoolSize = 4 // 核心线程数 // var corePoolSize = 4 // 核心线程数
var maximumPoolSize = 10 // 最大线程数 // var maximumPoolSize = 10 // 最大线程数
var keepAliveTime: Long = 120 // 非核心线程空闲存活时间 // var keepAliveTime: Long = 120 // 非核心线程空闲存活时间
var threadPoolExecutor = ThreadPoolExecutor( // var threadPoolExecutor = ThreadPoolExecutor(
corePoolSize, // corePoolSize,
maximumPoolSize, // maximumPoolSize,
keepAliveTime, // keepAliveTime,
TimeUnit.SECONDS, // TimeUnit.SECONDS,
LinkedBlockingQueue() // LinkedBlockingQueue()
// )
private val scope = MainScope()
private var pdfDocument: PDDocument? = null
private var pdfRender: PDFRenderer? = null
private val selectPayLoad = 0
private val refreshPayLoad = 1
init {
scope.launch(SupervisorJob() + Dispatchers.IO) {
pdfDocument = PdfBoxUtils.getPdfDocument(pdfPath, mPassword, uri)
pdfRender = PDFRenderer(pdfDocument)
val dataList = mutableListOf<PdfPageBean>()
repeat(pdfDocument?.numberOfPages ?: 0) {
dataList.add(PdfPageBean(it))
}
if (dataList.isNotEmpty()) {
dataList[0].isSelect = true
}
withContext(Dispatchers.Main) {
submitList(dataList)
initCallBack?.invoke(dataList.size)
}
items.forEachIndexed { index, pdfPageBean ->
val render = pdfRender ?: return@launch
if (pdfPageBean.pageDrawable != null) return@forEachIndexed
if (!isActive) return@launch
runCatching {
val drawable = PdfBoxUtils.getPdfDrawablePage(
context, index, previewScale, render
) )
pdfPageBean.pageDrawable = drawable
}.onFailure {
return@launch
}
withContext(Dispatchers.Main) {
pdfPageBean.pageDrawable?.let {
notifyItemChanged(index, refreshPayLoad)
}
}
}
}
}
override fun onBindViewHolder(
holder: PdfPagerViewHolder,
position: Int,
item: PdfPageBean?,
payloads: List<Any>
) {
if (payloads.isNotEmpty()) {
if (item == null) return
when (itemLayout) {
R.layout.item_pdf_pager -> {
val binding = ItemPdfPagerBinding.bind(holder.itemView)
if (payloads[0] == 0) {
binding.tvPagerIndex.isSelected = item.isSelect
binding.tvPagerIndex.text = (item.pageIndex + 1).toString()
binding.flBorder.isSelected = item.isSelect
} else if (payloads[0] == 1) {
binding.ivPager.setImageDrawable(item.pageDrawable)
}
}
R.layout.item_pdf_pager_split -> {
val binding = ItemPdfPagerSplitBinding.bind(holder.itemView)
if (payloads[0] == 0) {
binding.ivSelector.isSelected = item.isSelect
} else if (payloads[0] == 1) {
binding.ivPager.setImageDrawable(item.pageDrawable)
}
}
}
} else
super.onBindViewHolder(holder, position, item, payloads)
}
@SuppressLint("SetTextI18n") @SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: PdfPagerViewHolder, position: Int, item: PdfPageBean?) { override fun onBindViewHolder(holder: PdfPagerViewHolder, position: Int, item: PdfPageBean?) {
...@@ -47,16 +131,13 @@ class PdfPagerAdapter( ...@@ -47,16 +131,13 @@ class PdfPagerAdapter(
when (itemLayout) { when (itemLayout) {
R.layout.item_pdf_pager -> { R.layout.item_pdf_pager -> {
val binding = ItemPdfPagerBinding.bind(holder.itemView) val binding = ItemPdfPagerBinding.bind(holder.itemView)
val context = holder.itemView.context
binding.tvPagerIndex.isSelected = item.isSelect binding.tvPagerIndex.isSelected = item.isSelect
binding.tvPagerIndex.text = (item.pageIndex + 1).toString() binding.tvPagerIndex.text = (item.pageIndex + 1).toString()
binding.flBorder.isSelected = item.isSelect binding.flBorder.isSelected = item.isSelect
if (item.pageDrawable != null) { //if (item.pageDrawable != null) {
binding.ivPager.setImageDrawable(item.pageDrawable) binding.ivPager.setImageDrawable(item.pageDrawable)
} else { // }
loadPagerDrawable(context, item, binding.root, binding.ivPager)
}
binding.root.setOnClickListener { binding.root.setOnClickListener {
clickAction?.invoke(item.pageIndex) clickAction?.invoke(item.pageIndex)
} }
...@@ -65,14 +146,12 @@ class PdfPagerAdapter( ...@@ -65,14 +146,12 @@ class PdfPagerAdapter(
R.layout.item_pdf_pager_split -> { R.layout.item_pdf_pager_split -> {
val binding = ItemPdfPagerSplitBinding.bind(holder.itemView) val binding = ItemPdfPagerSplitBinding.bind(holder.itemView)
binding.ivSelector.isSelected = item.isSelect binding.ivSelector.isSelected = item.isSelect
if (item.pageDrawable != null) { // if (item.pageDrawable != null) {
binding.ivPager.setImageDrawable(item.pageDrawable) binding.ivPager.setImageDrawable(item.pageDrawable)
} else { //}
loadPagerDrawable(context, item, binding.root, binding.ivPager, 1.5f)
}
binding.ivSelector.setOnClickListener { binding.ivSelector.setOnClickListener {
item.isSelect = !item.isSelect item.isSelect = !item.isSelect
notifyItemChanged(position, "aaa") notifyItemChanged(position, selectPayLoad)
selectAction?.invoke(items.any { it.isSelect }, items.all { it.isSelect }) selectAction?.invoke(items.any { it.isSelect }, items.all { it.isSelect })
} }
} }
...@@ -81,28 +160,11 @@ class PdfPagerAdapter( ...@@ -81,28 +160,11 @@ class PdfPagerAdapter(
} }
private fun loadPagerDrawable( override fun onCreateViewHolder(
context: Context, context: Context,
item: PdfPageBean, parent: ViewGroup,
itemView: View, viewType: Int
iv: ImageView, ): PdfPagerViewHolder {
scale: Float = 1f
) {
threadPoolExecutor.execute {
runCatching {
val drawable = PdfBoxUtils.getPdfDrawablePage(context, pdfPath, mPassword, uri, item.pageIndex, scale)
item.pageDrawable = drawable
itemView.post {
item.pageDrawable?.let {
iv.setImageDrawable(it)
}
}
}
}
}
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): PdfPagerViewHolder {
return PdfPagerViewHolder(itemLayout.inflate(parent)) return PdfPagerViewHolder(itemLayout.inflate(parent))
} }
...@@ -126,4 +188,11 @@ class PdfPagerAdapter( ...@@ -126,4 +188,11 @@ class PdfPagerAdapter(
mPassword = password mPassword = password
notifyDataSetChanged() notifyDataSetChanged()
} }
fun release() {
scope.cancel()
pdfRender = null
pdfDocument?.close()
pdfDocument = null
}
} }
\ No newline at end of file
...@@ -7,7 +7,6 @@ import com.artifex.mupdfdemo.MuPDFCore ...@@ -7,7 +7,6 @@ import com.artifex.mupdfdemo.MuPDFCore
import com.artifex.mupdfdemo.OutlineActivityData import com.artifex.mupdfdemo.OutlineActivityData
import com.base.pdfviewerscannerwhite.R import com.base.pdfviewerscannerwhite.R
import com.base.pdfviewerscannerwhite.bean.ConstObject.MIME_TYPE_PDF import com.base.pdfviewerscannerwhite.bean.ConstObject.MIME_TYPE_PDF
import com.base.pdfviewerscannerwhite.bean.PdfPageBean
import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfMergeActivity.Companion.mergePdfList import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfMergeActivity.Companion.mergePdfList
import com.base.pdfviewerscannerwhite.utils.LogEx import com.base.pdfviewerscannerwhite.utils.LogEx
import com.base.pdfviewerscannerwhite.utils.UriUtils.readFileToByteArray import com.base.pdfviewerscannerwhite.utils.UriUtils.readFileToByteArray
...@@ -17,8 +16,7 @@ import java.io.File ...@@ -17,8 +16,7 @@ import java.io.File
class PdfPresenter( class PdfPresenter(
val context: Context, val context: Context
val pdfView: PdfView? = null
) { ) {
private val TAG = "PdfPresenter" private val TAG = "PdfPresenter"
var password: String? = null var password: String? = null
...@@ -41,25 +39,6 @@ class PdfPresenter( ...@@ -41,25 +39,6 @@ class PdfPresenter(
return muPDFCore return muPDFCore
} }
fun iniPdfPage(filePath: String, uri: String? = null) {
val list = arrayListOf<PdfPageBean>()
val number = PdfBoxUtils.getNumberOfPages(filePath, password, uri)
repeat(number) {
list.add(PdfPageBean(it))
}
pdfView?.initPdfPageRv(list)
}
fun iniPdfPage(pageCount: Int) {
val list = arrayListOf<PdfPageBean>()
repeat(pageCount) {
list.add(PdfPageBean(it))
}
pdfView?.initPdfPageRv(list)
}
fun splitPdf( fun splitPdf(
srcPath: String, srcPath: String,
newPath: String, newPath: String,
...@@ -118,7 +97,10 @@ class PdfPresenter( ...@@ -118,7 +97,10 @@ class PdfPresenter(
private fun createAppDocumentDir(): File { private fun createAppDocumentDir(): File {
val appName = context.resources.getString(R.string.app_name) val appName = context.resources.getString(R.string.app_name)
val appDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), appName) val appDir = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),
appName
)
if (!appDir.exists()) { if (!appDir.exists()) {
appDir.mkdirs() appDir.mkdirs()
} }
......
...@@ -4,7 +4,6 @@ import android.content.Intent ...@@ -4,7 +4,6 @@ import android.content.Intent
import androidx.activity.addCallback import androidx.activity.addCallback
import com.base.pdfviewerscannerwhite.R import com.base.pdfviewerscannerwhite.R
import com.base.pdfviewerscannerwhite.bean.ConstObject import com.base.pdfviewerscannerwhite.bean.ConstObject
import com.base.pdfviewerscannerwhite.bean.PdfPageBean
import com.base.pdfviewerscannerwhite.databinding.ActivityPdfSplitBinding import com.base.pdfviewerscannerwhite.databinding.ActivityPdfSplitBinding
import com.base.pdfviewerscannerwhite.helper.BaseActivity import com.base.pdfviewerscannerwhite.helper.BaseActivity
import com.base.pdfviewerscannerwhite.helper.MyApplication import com.base.pdfviewerscannerwhite.helper.MyApplication
...@@ -30,7 +29,7 @@ class PdfSplitActivity : BaseActivity<ActivityPdfSplitBinding>(), PdfView { ...@@ -30,7 +29,7 @@ class PdfSplitActivity : BaseActivity<ActivityPdfSplitBinding>(), PdfView {
} }
override fun initView() { override fun initView() {
pdfPresenter = PdfPresenter(this, this) pdfPresenter = PdfPresenter(this)
path = intent.extras?.getString("path", "") ?: "" path = intent.extras?.getString("path", "") ?: ""
pwd = intent.extras?.getString("pwd", "") ?: "" pwd = intent.extras?.getString("pwd", "") ?: ""
uri = intent.extras?.getString("uri") uri = intent.extras?.getString("uri")
...@@ -40,7 +39,7 @@ class PdfSplitActivity : BaseActivity<ActivityPdfSplitBinding>(), PdfView { ...@@ -40,7 +39,7 @@ class PdfSplitActivity : BaseActivity<ActivityPdfSplitBinding>(), PdfView {
initAdapter() initAdapter()
pdfPresenter.iniPdfPage(path, uri) //pdfPresenter.iniPdfPage(path, uri)
} }
override fun initListener() { override fun initListener() {
...@@ -71,7 +70,7 @@ class PdfSplitActivity : BaseActivity<ActivityPdfSplitBinding>(), PdfView { ...@@ -71,7 +70,7 @@ class PdfSplitActivity : BaseActivity<ActivityPdfSplitBinding>(), PdfView {
} }
private fun initAdapter() { private fun initAdapter() {
pdfPagerAdapter = PdfPagerAdapter(path, null, R.layout.item_pdf_pager_split) pdfPagerAdapter = PdfPagerAdapter(path, null, R.layout.item_pdf_pager_split, 1.5f)
pdfPagerAdapter.mPassword = pwd pdfPagerAdapter.mPassword = pwd
pdfPagerAdapter.selectAction = { enable, allSelect -> pdfPagerAdapter.selectAction = { enable, allSelect ->
binding.tvBtnSplit.isEnabled = enable binding.tvBtnSplit.isEnabled = enable
...@@ -81,8 +80,8 @@ class PdfSplitActivity : BaseActivity<ActivityPdfSplitBinding>(), PdfView { ...@@ -81,8 +80,8 @@ class PdfSplitActivity : BaseActivity<ActivityPdfSplitBinding>(), PdfView {
} }
override fun initPdfPageRv(items: List<PdfPageBean>) { override fun onDestroy() {
pdfPagerAdapter.submitList(items) super.onDestroy()
pdfPagerAdapter.release()
} }
} }
\ No newline at end of file
package com.base.pdfviewerscannerwhite.ui.document.pdf package com.base.pdfviewerscannerwhite.ui.document.pdf
import com.base.pdfviewerscannerwhite.bean.PdfPageBean
interface PdfView { interface PdfView {
fun initPdfPageRv(items: List<PdfPageBean>)
fun jumpPage(pageIndex: Int) = Unit fun jumpPage(pageIndex: Int) = Unit
fun jumpSplit() = Unit fun jumpSplit() = Unit
......
...@@ -71,9 +71,10 @@ class MainPresenter( ...@@ -71,9 +71,10 @@ class MainPresenter(
var mainRefreshData: Boolean = false var mainRefreshData: Boolean = false
} }
fun initAllDocumentData() = lifecycleScope.launch(Dispatchers.IO) { fun initAllDocumentData() {
if (!mainRefreshData) { if (!mainRefreshData) {
mainRefreshData = true mainRefreshData = true
lifecycleScope.launch(Dispatchers.IO) {
val start = System.currentTimeMillis() val start = System.currentTimeMillis()
Log.d("glc", "pdfs 清理前:" + pdfDocuments.size) Log.d("glc", "pdfs 清理前:" + pdfDocuments.size)
context.upDateDemoStore() context.upDateDemoStore()
...@@ -82,7 +83,17 @@ class MainPresenter( ...@@ -82,7 +83,17 @@ class MainPresenter(
ConstObject.haveSaveDemo = true ConstObject.haveSaveDemo = true
} }
val pdfs = initAllPdfData() val pdfs = initAllPdfData()
pdfs.map { it.state = PdfBoxUtils.checkPdfEncryption(it.path) } val largePdf = mutableListOf<DocumentBean>()
pdfs.map {
it.state = PdfBoxUtils.checkPdfEncryption(
it.path,
memUsageSetting = PdfBoxUtils.memoryUsageSetting.getPartitionedCopy(pdfs.size)
)
if (it.state == -1) largePdf.add(it)
}
largePdf.map {
it.state = PdfBoxUtils.checkPdfEncryption(it.path)
}
pdfDocuments.clear() pdfDocuments.clear()
wordDocuments.clear() wordDocuments.clear()
excelDocuments.clear() excelDocuments.clear()
...@@ -93,12 +104,13 @@ class MainPresenter( ...@@ -93,12 +104,13 @@ class MainPresenter(
wordDocuments.addAll(initAllWordData()) wordDocuments.addAll(initAllWordData())
excelDocuments.addAll(initAllExcelData()) excelDocuments.addAll(initAllExcelData())
pptDocuments.addAll(initAllPptData()) pptDocuments.addAll(initAllPptData())
mainRefreshData = false
withContext(Dispatchers.Main) { withContext(Dispatchers.Main) {
val end = System.currentTimeMillis() val end = System.currentTimeMillis()
val time = end - start val time = end - start
LogEx.logDebug(TAG, "time=$time") LogEx.logDebug(TAG, "time=$time")
mainView.refreshPageList() mainView.refreshPageList()
mainRefreshData = false
}
} }
} }
} }
...@@ -113,10 +125,18 @@ class MainPresenter( ...@@ -113,10 +125,18 @@ class MainPresenter(
when (documentType) { when (documentType) {
TYPE_PDF -> { TYPE_PDF -> {
val data = arrayListOf<DocumentBean>() val data = arrayListOf<DocumentBean>()
val largeData = mutableListOf<DocumentBean>()
data.addAll(pdfDocuments) data.addAll(pdfDocuments)
data.forEach { data.forEach {
it.isBookmarked = bookmarkList.contains(it.path) it.isBookmarked = bookmarkList.contains(it.path)
it.state = PdfBoxUtils.checkPdfEncryption(
it.path,
memUsageSetting = PdfBoxUtils.memoryUsageSetting.getPartitionedCopy(data.size)
)
if (it.state == -1) largeData.add(it)
}
largeData.forEach {
it.state = PdfBoxUtils.checkPdfEncryption(it.path) it.state = PdfBoxUtils.checkPdfEncryption(it.path)
} }
when (dataType) { when (dataType) {
......
package com.base.pdfviewerscannerwhite.utils
import android.net.Uri
import androidx.core.net.toUri
import com.base.pdfviewerscannerwhite.helper.MyApplication
import java.io.File
object Paths {
const val PdfDir = "pdf"
/**
* 应用存储文件的文件夹 (不需要读写权限)
* @name 子文件夹名称
*/
fun fileDir(name: String): File? {
return runCatching {
(MyApplication.context.getExternalFilesDir(name)?.apply {
if (!exists() || !isDirectory) {
mkdirs()
}
}) ?: (MyApplication.context.filesDir?.let {
File(it, name).apply {
if (!exists() || !isDirectory) {
mkdirs()
}
}
})
}.getOrNull()
}
/**
* 应用缓存文件夹 (不需要读写权限)
* @name 子文件夹名称
*/
fun cacheDir(name: String): File? {
return runCatching {
val dir = MyApplication.context.externalCacheDir ?: MyApplication.context.cacheDir
dir?.let {
File(it, name).apply {
if (!exists() || !isDirectory) {
mkdirs()
}
}
}
}.getOrNull()
}
fun String.toUriCompat(): Uri {
var uri = this.toUri()
if (uri.scheme.isNullOrEmpty()) {
uri = "file://$this".toUri()
}
return uri
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment