From 16d29aeb551ae86d0593d00603fbdbdaadb4b0d6 Mon Sep 17 00:00:00 2001 From: gedoor Date: Sat, 2 Jan 2021 12:09:48 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../io/legado/app/base/BaseDialogFragment.kt | 5 +- .../io/legado/app/data/entities/BookSource.kt | 93 ++++++++++--------- .../java/io/legado/app/help/ImageLoader.kt | 4 +- .../legado/app/help/storage/ImportOldData.kt | 50 +++++----- .../java/io/legado/app/lib/webdav/WebDav.kt | 10 +- .../io/legado/app/ui/about/AboutActivity.kt | 4 +- .../io/legado/app/ui/about/AboutFragment.kt | 6 +- .../legado/app/ui/book/read/TextActionMenu.kt | 14 +-- .../legado/app/ui/book/read/page/ReadView.kt | 4 +- .../read/page/provider/ChapterProvider.kt | 4 +- .../io/legado/app/ui/filepicker/FilePicker.kt | 20 ++-- .../app/ui/filepicker/entity/JavaBean.kt | 4 +- .../app/ui/filepicker/utils/ConvertUtils.kt | 20 ++-- .../app/ui/replace/ReplaceRuleActivity.kt | 6 +- .../ui/rss/source/manage/RssSourceActivity.kt | 6 +- .../legado/app/ui/widget/font/FontAdapter.kt | 8 +- .../io/legado/app/ui/widget/text/BadgeView.kt | 7 +- .../java/io/legado/app/utils/StringUtils.kt | 16 ++-- .../java/io/legado/app/utils/SystemUtils.kt | 6 +- .../io/legado/app/utils/ViewExtensions.kt | 8 +- 20 files changed, 131 insertions(+), 164 deletions(-) diff --git a/app/src/main/java/io/legado/app/base/BaseDialogFragment.kt b/app/src/main/java/io/legado/app/base/BaseDialogFragment.kt index 6b2ca45ba..468dd4c95 100644 --- a/app/src/main/java/io/legado/app/base/BaseDialogFragment.kt +++ b/app/src/main/java/io/legado/app/base/BaseDialogFragment.kt @@ -32,13 +32,10 @@ abstract class BaseDialogFragment : DialogFragment(), CoroutineScope { abstract fun onFragmentCreated(view: View, savedInstanceState: Bundle?) override fun show(manager: FragmentManager, tag: String?) { - try { + kotlin.runCatching { //在每个add事务前增加一个remove事务,防止连续的add manager.beginTransaction().remove(this).commit() super.show(manager, tag) - } catch (e: Exception) { - //同一实例使用不同的tag会异常,这里捕获一下 - e.printStackTrace() } } diff --git a/app/src/main/java/io/legado/app/data/entities/BookSource.kt b/app/src/main/java/io/legado/app/data/entities/BookSource.kt index 5604cec7c..b439fb367 100644 --- a/app/src/main/java/io/legado/app/data/entities/BookSource.kt +++ b/app/src/main/java/io/legado/app/data/entities/BookSource.kt @@ -46,14 +46,15 @@ data class BookSource( var ruleBookInfo: BookInfoRule? = null, // 书籍信息页规则 var ruleToc: TocRule? = null, // 目录页规则 var ruleContent: ContentRule? = null // 正文页规则 -): Parcelable, JsExtensions { - +) : Parcelable, JsExtensions { + override fun hashCode(): Int { return bookSourceUrl.hashCode() } - - override fun equals(other: Any?) = if (other is BookSource) other.bookSourceUrl == bookSourceUrl else false - + + override fun equals(other: Any?) = + if (other is BookSource) other.bookSourceUrl == bookSourceUrl else false + @Throws(Exception::class) fun getHeaderMap() = (HashMap().apply { this[AppConst.UA_NAME] = AppConfig.userAgent @@ -71,17 +72,17 @@ data class BookSource( } } }) as Map - + fun getSearchRule() = ruleSearch ?: SearchRule() - + fun getExploreRule() = ruleExplore ?: ExploreRule() - + fun getBookInfoRule() = ruleBookInfo ?: BookInfoRule() - + fun getTocRule() = ruleToc ?: TocRule() - + fun getContentRule() = ruleContent ?: ContentRule() - + fun addGroup(group: String) { bookSourceGroup?.let { if (!it.contains(group)) { @@ -91,20 +92,20 @@ data class BookSource( bookSourceGroup = group } } - + fun removeGroup(group: String) { bookSourceGroup?.splitNotBlank("[,;,;]".toRegex())?.toHashSet()?.let { it.remove(group) bookSourceGroup = TextUtils.join(",", it) } } - + fun getExploreKinds() = arrayListOf().apply { - exploreUrl?.let { - var a = it + exploreUrl?.let { urlRule -> + var a = urlRule if (a.isNotBlank()) { - try { - if (it.startsWith("", false)) { + kotlin.runCatching { + if (urlRule.startsWith("", false)) { val aCache = ACache.get(App.INSTANCE, "explore") a = aCache.getAsString(bookSourceUrl) ?: "" if (a.isBlank()) { @@ -114,7 +115,7 @@ data class BookSource( bindings["cookie"] = CookieStore bindings["cache"] = CacheManager a = AppConst.SCRIPT_ENGINE.eval( - it.substring(4, it.lastIndexOf("<")), + urlRule.substring(4, urlRule.lastIndexOf("<")), bindings ).toString() aCache.put(bookSourceUrl, a) @@ -126,13 +127,13 @@ data class BookSource( if (d.size > 1) add(ExploreKind(d[0], d[1])) } - } catch (e: Exception) { - add(ExploreKind(e.localizedMessage ?: "")) + }.onFailure { + add(ExploreKind(it.localizedMessage ?: "")) } } } } - + /** * 执行JS */ @@ -147,60 +148,60 @@ data class BookSource( fun equal(source: BookSource) = equal(bookSourceName, source.bookSourceName) - && equal(bookSourceUrl, source.bookSourceUrl) - && equal(bookSourceGroup, source.bookSourceGroup) - && bookSourceType == source.bookSourceType - && equal(bookUrlPattern, source.bookUrlPattern) - && equal(bookSourceComment, source.bookSourceComment) - && enabled == source.enabled - && enabledExplore == source.enabledExplore - && equal(header, source.header) - && equal(loginUrl, source.loginUrl) - && equal(exploreUrl, source.exploreUrl) - && equal(searchUrl, source.searchUrl) - && getSearchRule() == source.getSearchRule() - && getExploreRule() == source.getExploreRule() - && getBookInfoRule() == source.getBookInfoRule() - && getTocRule() == source.getTocRule() - && getContentRule() == source.getContentRule() - + && equal(bookSourceUrl, source.bookSourceUrl) + && equal(bookSourceGroup, source.bookSourceGroup) + && bookSourceType == source.bookSourceType + && equal(bookUrlPattern, source.bookUrlPattern) + && equal(bookSourceComment, source.bookSourceComment) + && enabled == source.enabled + && enabledExplore == source.enabledExplore + && equal(header, source.header) + && equal(loginUrl, source.loginUrl) + && equal(exploreUrl, source.exploreUrl) + && equal(searchUrl, source.searchUrl) + && getSearchRule() == source.getSearchRule() + && getExploreRule() == source.getExploreRule() + && getBookInfoRule() == source.getBookInfoRule() + && getTocRule() == source.getTocRule() + && getContentRule() == source.getContentRule() + private fun equal(a: String?, b: String?) = a == b || (a.isNullOrEmpty() && b.isNullOrEmpty()) data class ExploreKind( var title: String, var url: String? = null ) - + class Converters { @TypeConverter fun exploreRuleToString(exploreRule: ExploreRule?): String = GSON.toJson(exploreRule) - + @TypeConverter fun stringToExploreRule(json: String?) = GSON.fromJsonObject(json) @TypeConverter fun searchRuleToString(searchRule: SearchRule?): String = GSON.toJson(searchRule) - + @TypeConverter fun stringToSearchRule(json: String?) = GSON.fromJsonObject(json) @TypeConverter fun bookInfoRuleToString(bookInfoRule: BookInfoRule?): String = GSON.toJson(bookInfoRule) - + @TypeConverter fun stringToBookInfoRule(json: String?) = GSON.fromJsonObject(json) @TypeConverter fun tocRuleToString(tocRule: TocRule?): String = GSON.toJson(tocRule) - + @TypeConverter fun stringToTocRule(json: String?) = GSON.fromJsonObject(json) - + @TypeConverter fun contentRuleToString(contentRule: ContentRule?): String = GSON.toJson(contentRule) - + @TypeConverter fun stringToContentRule(json: String?) = GSON.fromJsonObject(json) - + } } \ No newline at end of file diff --git a/app/src/main/java/io/legado/app/help/ImageLoader.kt b/app/src/main/java/io/legado/app/help/ImageLoader.kt index 2184d03d3..cc702ff0f 100644 --- a/app/src/main/java/io/legado/app/help/ImageLoader.kt +++ b/app/src/main/java/io/legado/app/help/ImageLoader.kt @@ -22,9 +22,9 @@ object ImageLoader { path.isNullOrEmpty() -> Glide.with(context).load(path) path.isAbsUrl() -> Glide.with(context).load(AnalyzeUrl(path).getGlideUrl()) path.isContentScheme() -> Glide.with(context).load(Uri.parse(path)) - else -> try { + else -> kotlin.runCatching { Glide.with(context).load(File(path)) - } catch (e: Exception) { + }.getOrElse { Glide.with(context).load(path) } } diff --git a/app/src/main/java/io/legado/app/help/storage/ImportOldData.kt b/app/src/main/java/io/legado/app/help/storage/ImportOldData.kt index 33827f829..178f8369a 100644 --- a/app/src/main/java/io/legado/app/help/storage/ImportOldData.kt +++ b/app/src/main/java/io/legado/app/help/storage/ImportOldData.kt @@ -15,61 +15,61 @@ object ImportOldData { fun importUri(context: Context, uri: Uri) { if (uri.isContentScheme()) { - DocumentFile.fromTreeUri(context, uri)?.listFiles()?.forEach { - when (it.name) { + DocumentFile.fromTreeUri(context, uri)?.listFiles()?.forEach { doc -> + when (doc.name) { "myBookShelf.json" -> - try { - DocumentUtils.readText(context, it.uri)?.let { json -> + kotlin.runCatching { + DocumentUtils.readText(context, doc.uri)?.let { json -> val importCount = importOldBookshelf(json) context.toast("成功导入书籍${importCount}") } - } catch (e: java.lang.Exception) { - context.toast("导入书籍失败\n${e.localizedMessage}") + }.onFailure { + context.toast("导入书籍失败\n${it.localizedMessage}") } "myBookSource.json" -> - try { - DocumentUtils.readText(context, it.uri)?.let { json -> + kotlin.runCatching { + DocumentUtils.readText(context, doc.uri)?.let { json -> val importCount = importOldSource(json) context.toast("成功导入书源${importCount}") } - } catch (e: Exception) { - context.toast("导入源失败\n${e.localizedMessage}") + }.onFailure { + context.toast("导入源失败\n${it.localizedMessage}") } "myBookReplaceRule.json" -> - try { - DocumentUtils.readText(context, it.uri)?.let { json -> + kotlin.runCatching { + DocumentUtils.readText(context, doc.uri)?.let { json -> val importCount = importOldReplaceRule(json) context.toast("成功导入替换规则${importCount}") } - } catch (e: Exception) { - context.toast("导入替换规则失败\n${e.localizedMessage}") + }.onFailure { + context.toast("导入替换规则失败\n${it.localizedMessage}") } } } } else { - uri.path?.let { - val file = File(it) - try {// 导入书架 + uri.path?.let { path -> + val file = File(path) + kotlin.runCatching {// 导入书架 val shelfFile = FileUtils.createFileIfNotExist(file, "myBookShelf.json") val json = shelfFile.readText() val importCount = importOldBookshelf(json) context.toast("成功导入书籍${importCount}") - } catch (e: Exception) { - context.toast("导入书籍失败\n${e.localizedMessage}") + }.onFailure { + context.toast("导入书籍失败\n${it.localizedMessage}") } - try {// Book source + kotlin.runCatching {// Book source val sourceFile = FileUtils.getFile(file, "myBookSource.json") val json = sourceFile.readText() val importCount = importOldSource(json) context.toast("成功导入书源${importCount}") - } catch (e: Exception) { - context.toast("导入源失败\n${e.localizedMessage}") + }.onFailure { + context.toast("导入源失败\n${it.localizedMessage}") } - try {// Replace rules + kotlin.runCatching {// Replace rules val ruleFile = FileUtils.getFile(file, "myBookReplaceRule.json") if (ruleFile.exists()) { val json = ruleFile.readText() @@ -78,8 +78,8 @@ object ImportOldData { } else { context.toast("未找到替换规则") } - } catch (e: Exception) { - context.toast("导入替换规则失败\n${e.localizedMessage}") + }.onFailure { + context.toast("导入替换规则失败\n${it.localizedMessage}") } } } diff --git a/app/src/main/java/io/legado/app/lib/webdav/WebDav.kt b/app/src/main/java/io/legado/app/lib/webdav/WebDav.kt index cfcf094ad..dafedc128 100644 --- a/app/src/main/java/io/legado/app/lib/webdav/WebDav.kt +++ b/app/src/main/java/io/legado/app/lib/webdav/WebDav.kt @@ -12,7 +12,6 @@ import rxhttp.wrapper.param.toInputStream import java.io.File import java.io.IOException import java.io.InputStream -import java.io.UnsupportedEncodingException import java.net.MalformedURLException import java.net.URL import java.net.URLEncoder @@ -39,15 +38,12 @@ class WebDav(urlStr: String) { private val url: URL = URL(urlStr) private val httpUrl: String? by lazy { val raw = url.toString().replace("davs://", "https://").replace("dav://", "http://") - try { - return@lazy URLEncoder.encode(raw, "UTF-8") + return@lazy kotlin.runCatching { + URLEncoder.encode(raw, "UTF-8") .replace("\\+".toRegex(), "%20") .replace("%3A".toRegex(), ":") .replace("%2F".toRegex(), "/") - } catch (e: UnsupportedEncodingException) { - e.printStackTrace() - return@lazy null - } + }.getOrNull() } val host: String? get() = url.host val path get() = url.toString() diff --git a/app/src/main/java/io/legado/app/ui/about/AboutActivity.kt b/app/src/main/java/io/legado/app/ui/about/AboutActivity.kt index abfa31b03..f6c9088de 100644 --- a/app/src/main/java/io/legado/app/ui/about/AboutActivity.kt +++ b/app/src/main/java/io/legado/app/ui/about/AboutActivity.kt @@ -30,7 +30,7 @@ class AboutActivity : BaseActivity() { .replace(R.id.fl_fragment, aboutFragment, fTag) .commit() binding.tvAppSummary.post { - try { + kotlin.runCatching { val span = ForegroundColorSpan(accentColor) val spannableString = SpannableString(binding.tvAppSummary.text) val gzh = getString(R.string.legado_gzh) @@ -40,8 +40,6 @@ class AboutActivity : BaseActivity() { Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) binding.tvAppSummary.text = spannableString - } catch (e: Exception) { - e.printStackTrace() } } } diff --git a/app/src/main/java/io/legado/app/ui/about/AboutFragment.kt b/app/src/main/java/io/legado/app/ui/about/AboutFragment.kt index 68ff8d0fa..010be8839 100644 --- a/app/src/main/java/io/legado/app/ui/about/AboutFragment.kt +++ b/app/src/main/java/io/legado/app/ui/about/AboutFragment.kt @@ -93,12 +93,10 @@ class AboutFragment : PreferenceFragmentCompat() { Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D$key") // 此Flag可根据具体产品需要自定义,如设置,则在加群界面按返回,返回手Q主界面,不设置,按返回会返回到呼起产品界面 // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - return try { + return kotlin.runCatching { startActivity(intent) true - } catch (e: java.lang.Exception) { - false - } + }.getOrDefault(false) } } \ No newline at end of file diff --git a/app/src/main/java/io/legado/app/ui/book/read/TextActionMenu.kt b/app/src/main/java/io/legado/app/ui/book/read/TextActionMenu.kt index 6ec4d86fe..4a75e05c0 100644 --- a/app/src/main/java/io/legado/app/ui/book/read/TextActionMenu.kt +++ b/app/src/main/java/io/legado/app/ui/book/read/TextActionMenu.kt @@ -130,7 +130,7 @@ class TextActionMenu(private val context: Context, private val callBack: CallBac readAloud(callBack.selectedText) } R.id.menu_browser -> { - try { + kotlin.runCatching { val intent = if (callBack.selectedText.isAbsUrl()) { Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(callBack.selectedText) @@ -141,9 +141,9 @@ class TextActionMenu(private val context: Context, private val callBack: CallBac } } context.startActivity(intent) - } catch (e: Exception) { - e.printStackTrace() - context.toast(e.localizedMessage ?: "ERROR") + }.onFailure { + it.printStackTrace() + context.toast(it.localizedMessage ?: "ERROR") } } else -> item.intent?.let { @@ -210,7 +210,7 @@ class TextActionMenu(private val context: Context, private val callBack: CallBac */ @RequiresApi(Build.VERSION_CODES.M) private fun onInitializeMenu(menu: Menu) { - try { + kotlin.runCatching { var menuItemOrder = 100 for (resolveInfo in getSupportedActivities()) { menu.add( @@ -218,8 +218,8 @@ class TextActionMenu(private val context: Context, private val callBack: CallBac menuItemOrder++, resolveInfo.loadLabel(context.packageManager) ).intent = createProcessTextIntentForResolveInfo(resolveInfo) } - } catch (e: Exception) { - context.toast("获取文字操作菜单出错:${e.localizedMessage}") + }.onFailure { + context.toast("获取文字操作菜单出错:${it.localizedMessage}") } } diff --git a/app/src/main/java/io/legado/app/ui/book/read/page/ReadView.kt b/app/src/main/java/io/legado/app/ui/book/read/page/ReadView.kt index 25803ac2a..8bc72438b 100644 --- a/app/src/main/java/io/legado/app/ui/book/read/page/ReadView.kt +++ b/app/src/main/java/io/legado/app/ui/book/read/page/ReadView.kt @@ -338,10 +338,10 @@ class ReadView(context: Context, attrs: AttributeSet) : } end -= 1 } - try { + kotlin.runCatching { curPage.selectStartMoveIndex(firstRelativePage, lineStart, start) curPage.selectEndMoveIndex(firstRelativePage, lineEnd, end) - } catch (e: Exception) { + }.onFailure { print( """ curPage.selectStartMoveIndex($firstRelativePage, $lineStart, $start) diff --git a/app/src/main/java/io/legado/app/ui/book/read/page/provider/ChapterProvider.kt b/app/src/main/java/io/legado/app/ui/book/read/page/provider/ChapterProvider.kt index 4895e2373..af7f8ecd8 100644 --- a/app/src/main/java/io/legado/app/ui/book/read/page/provider/ChapterProvider.kt +++ b/app/src/main/java/io/legado/app/ui/book/read/page/provider/ChapterProvider.kt @@ -352,7 +352,7 @@ object ChapterProvider { } private fun getTypeface(fontPath: String): Typeface { - return try { + return kotlin.runCatching { when { fontPath.isContentScheme() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> { val fd = App.INSTANCE.contentResolver @@ -370,7 +370,7 @@ object ChapterProvider { else -> Typeface.SANS_SERIF } } - } catch (e: Exception) { + }.getOrElse { ReadBookConfig.textFont = "" ReadBookConfig.save() Typeface.SANS_SERIF diff --git a/app/src/main/java/io/legado/app/ui/filepicker/FilePicker.kt b/app/src/main/java/io/legado/app/ui/filepicker/FilePicker.kt index 631b2da66..b464c1657 100644 --- a/app/src/main/java/io/legado/app/ui/filepicker/FilePicker.kt +++ b/app/src/main/java/io/legado/app/ui/filepicker/FilePicker.kt @@ -30,11 +30,10 @@ object FilePicker { items(selectList) { _, index -> when (index) { 0 -> { - try { + kotlin.runCatching { val intent = createSelectDirIntent() activity.startActivityForResult(intent, requestCode) - } catch (e: java.lang.Exception) { - e.printStackTrace() + }.onFailure { checkPermissions(activity) { FilePickerDialog.show( activity.supportFragmentManager, @@ -81,11 +80,10 @@ object FilePicker { items(selectList) { _, index -> when (index) { 0 -> { - try { + kotlin.runCatching { val intent = createSelectDirIntent() fragment.startActivityForResult(intent, requestCode) - } catch (e: java.lang.Exception) { - e.printStackTrace() + }.onFailure { checkPermissions(fragment) { FilePickerDialog.show( fragment.childFragmentManager, @@ -133,15 +131,14 @@ object FilePicker { items(selectList) { _, index -> when (index) { 0 -> { - try { + kotlin.runCatching { val intent = createSelectFileIntent() intent.putExtra( Intent.EXTRA_MIME_TYPES, typesOfExtensions(allowExtensions) ) activity.startActivityForResult(intent, requestCode) - } catch (e: java.lang.Exception) { - e.printStackTrace() + }.onFailure { checkPermissions(activity) { FilePickerDialog.show( activity.supportFragmentManager, @@ -191,15 +188,14 @@ object FilePicker { items(selectList) { _, index -> when (index) { 0 -> { - try { + kotlin.runCatching { val intent = createSelectFileIntent() intent.putExtra( Intent.EXTRA_MIME_TYPES, typesOfExtensions(allowExtensions) ) fragment.startActivityForResult(intent, requestCode) - } catch (e: java.lang.Exception) { - e.printStackTrace() + }.onFailure { checkPermissions(fragment) { FilePickerDialog.show( fragment.childFragmentManager, diff --git a/app/src/main/java/io/legado/app/ui/filepicker/entity/JavaBean.kt b/app/src/main/java/io/legado/app/ui/filepicker/entity/JavaBean.kt index c23a827fb..a6fb0c2bc 100644 --- a/app/src/main/java/io/legado/app/ui/filepicker/entity/JavaBean.kt +++ b/app/src/main/java/io/legado/app/ui/filepicker/entity/JavaBean.kt @@ -34,15 +34,13 @@ open class JavaBean : Serializable { val fields = list.toTypedArray() for (field in fields) { val fieldName = field.name - try { + kotlin.runCatching { val obj = field.get(this) sb.append(fieldName) sb.append("=") sb.append(obj) sb.append("\n") - } catch (ignored: IllegalAccessException) { } - } return sb.toString() } diff --git a/app/src/main/java/io/legado/app/ui/filepicker/utils/ConvertUtils.kt b/app/src/main/java/io/legado/app/ui/filepicker/utils/ConvertUtils.kt index 1af75ebe8..b4f0f0b7e 100644 --- a/app/src/main/java/io/legado/app/ui/filepicker/utils/ConvertUtils.kt +++ b/app/src/main/java/io/legado/app/ui/filepicker/utils/ConvertUtils.kt @@ -6,7 +6,6 @@ import android.graphics.BitmapFactory import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import java.io.BufferedReader -import java.io.IOException import java.io.InputStream import java.io.InputStreamReader import java.text.DecimalFormat @@ -24,11 +23,9 @@ object ConvertUtils { const val KB: Long = 1024 fun toInt(obj: Any): Int { - return try { + return kotlin.runCatching { Integer.parseInt(obj.toString()) - } catch (e: NumberFormatException) { - -1 - } + }.getOrDefault(-1) } fun toInt(bytes: ByteArray): Int { @@ -42,11 +39,9 @@ object ConvertUtils { } fun toFloat(obj: Any): Float { - return try { + return kotlin.runCatching { java.lang.Float.parseFloat(obj.toString()) - } catch (e: NumberFormatException) { - -1f - } + }.getOrDefault(-1f) } fun toString(objects: Array, tag: String): String { @@ -62,7 +57,7 @@ object ConvertUtils { fun toBitmap(bytes: ByteArray, width: Int = -1, height: Int = -1): Bitmap? { var bitmap: Bitmap? = null if (bytes.isNotEmpty()) { - try { + kotlin.runCatching { val options = BitmapFactory.Options() // 设置让解码器以最佳方式解码 options.inPreferredConfig = null @@ -72,7 +67,6 @@ object ConvertUtils { } bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) bitmap!!.density = 96// 96 dpi - } catch (e: Exception) { } } return bitmap @@ -101,7 +95,7 @@ object ConvertUtils { @JvmOverloads fun toString(`is`: InputStream, charset: String = "utf-8"): String { val sb = StringBuilder() - try { + kotlin.runCatching { val reader = BufferedReader(InputStreamReader(`is`, charset)) while (true) { val line = reader.readLine() @@ -113,9 +107,7 @@ object ConvertUtils { } reader.close() `is`.close() - } catch (e: IOException) { } - return sb.toString() } diff --git a/app/src/main/java/io/legado/app/ui/replace/ReplaceRuleActivity.kt b/app/src/main/java/io/legado/app/ui/replace/ReplaceRuleActivity.kt index 118992269..5710f929a 100644 --- a/app/src/main/java/io/legado/app/ui/replace/ReplaceRuleActivity.kt +++ b/app/src/main/java/io/legado/app/ui/replace/ReplaceRuleActivity.kt @@ -246,13 +246,13 @@ class ReplaceRuleActivity : VMBaseActivity if (resultCode == Activity.RESULT_OK) { data?.data?.let { uri -> - try { + kotlin.runCatching { uri.readText(this)?.let { val dataKey = IntentDataHelp.putData(it) startActivity("dataKey" to dataKey) } - } catch (e: Exception) { - toast("readTextError:${e.localizedMessage}") + }.onFailure { + toast("readTextError:${it.localizedMessage}") } } } diff --git a/app/src/main/java/io/legado/app/ui/rss/source/manage/RssSourceActivity.kt b/app/src/main/java/io/legado/app/ui/rss/source/manage/RssSourceActivity.kt index e6db8c73e..717278bd8 100644 --- a/app/src/main/java/io/legado/app/ui/rss/source/manage/RssSourceActivity.kt +++ b/app/src/main/java/io/legado/app/ui/rss/source/manage/RssSourceActivity.kt @@ -257,13 +257,13 @@ class RssSourceActivity : VMBaseActivity if (resultCode == Activity.RESULT_OK) { data?.data?.let { uri -> - try { + kotlin.runCatching { uri.readText(this)?.let { val dataKey = IntentDataHelp.putData(it) startActivity("dataKey" to dataKey) } - } catch (e: Exception) { - toast("readTextError:${e.localizedMessage}") + }.onFailure { + toast("readTextError:${it.localizedMessage}") } } } diff --git a/app/src/main/java/io/legado/app/ui/widget/font/FontAdapter.kt b/app/src/main/java/io/legado/app/ui/widget/font/FontAdapter.kt index c2b1619be..9f8bb77ca 100644 --- a/app/src/main/java/io/legado/app/ui/widget/font/FontAdapter.kt +++ b/app/src/main/java/io/legado/app/ui/widget/font/FontAdapter.kt @@ -29,7 +29,7 @@ class FontAdapter(context: Context, val callBack: CallBack) : payloads: MutableList ) { with(binding) { - try { + kotlin.runCatching { val typeface: Typeface? = if (item.isContentPath) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.contentResolver @@ -44,9 +44,9 @@ class FontAdapter(context: Context, val callBack: CallBack) : Typeface.createFromFile(item.uri.toString()) } tvFont.typeface = typeface - } catch (e: Exception) { - e.printStackTrace() - context.toast("Read ${item.name} Error: ${e.localizedMessage}") + }.onFailure { + it.printStackTrace() + context.toast("Read ${item.name} Error: ${it.localizedMessage}") } tvFont.text = item.name root.onClick { callBack.onClick(item) } diff --git a/app/src/main/java/io/legado/app/ui/widget/text/BadgeView.kt b/app/src/main/java/io/legado/app/ui/widget/text/BadgeView.kt index 4f26a9ad2..4bde81262 100644 --- a/app/src/main/java/io/legado/app/ui/widget/text/BadgeView.kt +++ b/app/src/main/java/io/legado/app/ui/widget/text/BadgeView.kt @@ -43,12 +43,9 @@ class BadgeView @JvmOverloads constructor( return null } val text = text.toString() - return try { + return kotlin.runCatching { Integer.parseInt(text) - } catch (e: NumberFormatException) { - null - } - + }.getOrNull() } var badgeGravity: Int diff --git a/app/src/main/java/io/legado/app/utils/StringUtils.kt b/app/src/main/java/io/legado/app/utils/StringUtils.kt index b810ffa0d..feb428337 100644 --- a/app/src/main/java/io/legado/app/utils/StringUtils.kt +++ b/app/src/main/java/io/legado/app/utils/StringUtils.kt @@ -3,7 +3,6 @@ package io.legado.app.utils import android.annotation.SuppressLint import android.text.TextUtils.isEmpty import java.text.DecimalFormat -import java.text.ParseException import java.text.SimpleDateFormat import java.util.* import java.util.regex.Matcher @@ -56,7 +55,7 @@ object StringUtils { @SuppressLint("SimpleDateFormat") val format = SimpleDateFormat(pattern) val calendar = Calendar.getInstance() - try { + kotlin.runCatching { val date = format.parse(source) ?: return "" val curTime = calendar.timeInMillis calendar.time = date @@ -95,8 +94,8 @@ object StringUtils { convertFormat.format(date) } } - } catch (e: ParseException) { - e.printStackTrace() + }.onFailure { + it.printStackTrace() } return "" @@ -173,7 +172,7 @@ object StringUtils { } // "一千零二十五", "一千二" 形式 - try { + return kotlin.runCatching { for (i in cn.indices) { val tmpNum = ChnMap[cn[i]]!! when { @@ -204,11 +203,8 @@ object StringUtils { } } result += tmp + billion - return result - } catch (e: Exception) { - return -1 - } - + result + }.getOrDefault(-1) } fun stringToInt(str: String?): Int { diff --git a/app/src/main/java/io/legado/app/utils/SystemUtils.kt b/app/src/main/java/io/legado/app/utils/SystemUtils.kt index 7faccc935..4625ebeb1 100644 --- a/app/src/main/java/io/legado/app/utils/SystemUtils.kt +++ b/app/src/main/java/io/legado/app/utils/SystemUtils.kt @@ -19,13 +19,13 @@ object SystemUtils { fun getScreenOffTime(context: Context): Int { var screenOffTime = 0 - try { + kotlin.runCatching { screenOffTime = Settings.System.getInt( context.contentResolver, Settings.System.SCREEN_OFF_TIMEOUT ) - } catch (e: Exception) { - e.printStackTrace() + }.onFailure { + it.printStackTrace() } return screenOffTime diff --git a/app/src/main/java/io/legado/app/utils/ViewExtensions.kt b/app/src/main/java/io/legado/app/utils/ViewExtensions.kt index 122f814a0..988072bb3 100644 --- a/app/src/main/java/io/legado/app/utils/ViewExtensions.kt +++ b/app/src/main/java/io/legado/app/utils/ViewExtensions.kt @@ -107,13 +107,11 @@ fun RadioGroup.checkByIndex(index: Int) { @SuppressLint("RestrictedApi") fun PopupMenu.show(x: Int, y: Int) { - try { + kotlin.runCatching { val field: Field = this.javaClass.getDeclaredField("mPopup") field.isAccessible = true (field.get(this) as MenuPopupHelper).show(x, y) - } catch (e: NoSuchFieldException) { - e.printStackTrace() - } catch (e: IllegalAccessException) { - e.printStackTrace() + }.onFailure { + it.printStackTrace() } } \ No newline at end of file