add fun runOnIO

pull/840/head
gedoor 4 years ago
parent e360ef66f5
commit a2951ebae3
  1. 8
      app/src/main/java/io/legado/app/utils/ContextExtensions.kt
  2. 21
      app/src/main/java/io/legado/app/utils/HandlerUtils.kt
  3. 16
      app/src/main/java/io/legado/app/web/SourceDebugWebSocket.kt

@ -36,25 +36,25 @@ inline fun <reified T : Service> Context.startService(configIntent: Intent.() ->
}
fun Context.toastOnUi(message: Int) {
runOnUiThread {
runOnUI {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}
fun Context.toastOnUi(message: CharSequence?) {
runOnUiThread {
runOnUI {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}
fun Context.longToastOnUi(message: Int) {
runOnUiThread {
runOnUI {
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
}
fun Context.longToastOnUi(message: CharSequence?) {
runOnUiThread {
runOnUI {
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
}

@ -1,8 +1,13 @@
@file:Suppress("unused")
package io.legado.app.utils
import android.os.Build.VERSION.SDK_INT
import android.os.Handler
import android.os.Looper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch
/** This main looper cache avoids synchronization overhead when accessed repeatedly. */
@JvmField
@ -28,10 +33,20 @@ val mainHandler: Handler = if (SDK_INT >= 28) Handler.createAsync(mainLooper) el
Handler(mainLooper) // Hidden constructor absent. Fall back to non-async constructor.
}
fun runOnUiThread(f: () -> Unit) {
fun runOnUI(function: () -> Unit) {
if (isMainThread) {
f()
function()
} else {
mainHandler.post(function)
}
}
fun CoroutineScope.runOnIO(function: () -> Unit) {
if (isMainThread) {
launch(IO) {
function()
}
} else {
mainHandler.post(f)
function()
}
}

@ -1,7 +1,6 @@
package io.legado.app.web
import android.os.Looper
import fi.iki.elonen.NanoHTTPD
import fi.iki.elonen.NanoWSD
import io.legado.app.App
@ -11,6 +10,7 @@ import io.legado.app.model.webBook.WebBook
import io.legado.app.utils.GSON
import io.legado.app.utils.fromJsonObject
import io.legado.app.utils.isJson
import io.legado.app.utils.runOnIO
import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers.IO
import splitties.init.appCtx
@ -77,19 +77,7 @@ class SourceDebugWebSocket(handshakeRequest: NanoHTTPD.IHTTPSession) :
}
override fun printLog(state: Int, msg: String) {
if (Looper.getMainLooper() == Looper.myLooper()) {
launch(IO) {
runCatching {
send(msg)
if (state == -1 || state == 1000) {
Debug.cancelDebug(true)
close(NanoWSD.WebSocketFrame.CloseCode.NormalClosure, "调试结束", false)
}
}.onFailure {
it.printStackTrace()
}
}
} else {
runOnIO {
runCatching {
send(msg)
if (state == -1 || state == 1000) {

Loading…
Cancel
Save